@tailor-platform/sdk 2.11.0 → 2.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/dist/application-BFTkaW6X.mjs +1 -0
  3. package/dist/{application-CcrP-v7z.mjs → application-D3HlhR3i.mjs} +2 -2
  4. package/dist/{application-CcrP-v7z.mjs.map → application-D3HlhR3i.mjs.map} +1 -1
  5. package/dist/cli/commands/generate/seed/bundler.d.mts +2 -2
  6. package/dist/cli/commands/tailordb/migrate/bundler.d.mts +1 -1
  7. package/dist/cli/commands/workspace/user/remove.d.mts +1 -1
  8. package/dist/cli/commands/workspace/user/update.d.mts +1 -1
  9. package/dist/cli/lib.mjs +1 -1
  10. package/dist/cli/main.mjs +41 -42
  11. package/dist/cli/main.mjs.map +1 -1
  12. package/dist/cli/shared/script-executor.d.mts +2 -2
  13. package/dist/completion/zsh-worker.zsh +32 -2
  14. package/dist/kysely-type-B-BOlXH7.mjs +43 -0
  15. package/dist/kysely-type-B-BOlXH7.mjs.map +1 -0
  16. package/dist/plugin/builtin/kysely-type/index.mjs +1 -1
  17. package/dist/{register-ts-hook-YqgUg8P7.mjs → register-ts-hook-CoZS-8Mx.mjs} +14 -14
  18. package/dist/register-ts-hook-CoZS-8Mx.mjs.map +1 -0
  19. package/dist/seed-CMkupmX8.mjs.map +1 -1
  20. package/dist/service_pb-CFVlGYdr.mjs +1 -0
  21. package/dist/{service_pb-BNxUPfP3.mjs → service_pb-CxHztLk1.mjs} +2 -2
  22. package/dist/{service_pb-BNxUPfP3.mjs.map → service_pb-CxHztLk1.mjs.map} +1 -1
  23. package/dist/tailor-proto/src/tailor/v1/auth_resource_pb.d.mts +10 -0
  24. package/dist/workflow-Cs9ISw6j.mjs.map +1 -1
  25. package/dist/workspace_resource_pb-u9bj6p3i.mjs +2 -0
  26. package/dist/workspace_resource_pb-u9bj6p3i.mjs.map +1 -0
  27. package/docs/cli/user.md +84 -21
  28. package/docs/cli-reference.md +1 -0
  29. package/package.json +6 -6
  30. package/dist/application-B4tCGHiQ.mjs +0 -1
  31. package/dist/kysely-type-CmvAz1Xj.mjs +0 -43
  32. package/dist/kysely-type-CmvAz1Xj.mjs.map +0 -1
  33. package/dist/register-ts-hook-YqgUg8P7.mjs.map +0 -1
  34. package/dist/service_pb-D-xFu9Ub.mjs +0 -1
  35. package/dist/workspace_resource_pb-B7S-zx4Z.mjs +0 -2
  36. package/dist/workspace_resource_pb-B7S-zx4Z.mjs.map +0 -1
package/dist/cli/main.mjs CHANGED
@@ -1,36 +1,36 @@
1
1
  #!/usr/bin/env node
2
- import{r as e}from"../schema-6d_OHyZf.mjs";import{E as t,Ft as n,Ht as r,Ot as i,q as a}from"../workspace_resource_pb-B7S-zx4Z.mjs";import{t as o}from"../assert-WeXvmG4j.mjs";import{a as s,n as c,r as l}from"../logger-CCjs1DuH.mjs";import{$ as u,$n as d,$r as f,$t as p,An as m,Ar as h,B as g,Br as _,C as v,Cn as y,Cr as b,Ct as x,Dn as S,Dr as C,Dt as w,E as ee,En as T,Er as te,Fn as E,Fr as D,Ft as ne,Gn as re,Gr as O,Hn as ie,Ht as ae,I as oe,In as k,Ir as se,Jn as ce,K as le,Kn as ue,Kt as de,L as fe,Lr as pe,M as me,Mn as he,Mr as ge,Mt as _e,N as ve,Nn as ye,Nr as A,Nt as be,O as xe,On as Se,Or as Ce,P as we,Pn as Te,Pr as j,Qn as Ee,Qr as De,R as Oe,Rr as ke,Sn as Ae,Sr as M,St as je,Tn as Me,Tr as Ne,Tt as Pe,Un as Fe,Ur as Ie,V as Le,Vr as N,W as Re,Wr as ze,Wt as Be,X as Ve,Xr as He,Xt as Ue,Yn as We,Yr as Ge,Yt as Ke,Z as qe,Zn as Je,Zr as Ye,_n as Xe,_r as Ze,_t as Qe,a as $e,an as et,ar as tt,at as nt,bn as rt,br as it,bt as at,c as ot,cr as P,dr as st,dt as ct,ei as F,en as lt,er as ut,f as dt,fn as ft,fr as pt,g as mt,gn as ht,gr as gt,gt as _t,hn as vt,hr as yt,in as bt,ir as xt,j as St,jn as Ct,jr as wt,kn as Tt,kr as Et,kt as Dt,lr as Ot,lt as kt,m as At,mn as jt,mr as I,nn as Mt,nr as Nt,o as Pt,or as Ft,pn as It,pr as Lt,pt as Rt,q as zt,qr as L,r as Bt,rr as Vt,rt as Ht,sn as Ut,sr as Wt,st as Gt,t as Kt,tn as qt,tr as Jt,tt as Yt,u as Xt,un as Zt,ur as Qt,v as $t,vn as en,vr as tn,w as nn,wn as rn,wr as an,wt as on,x as sn,xn as cn,xr as R,xt as ln,yn as un,yr as z,yt as dn,z as fn,zr as pn,zt as mn}from"../register-ts-hook-YqgUg8P7.mjs";import{$ as hn,A as gn,B as _n,D as vn,E as yn,G as bn,H as xn,J as Sn,K as Cn,M as wn,O as Tn,Q as B,T as En,V as Dn,W as V,X as On,Y as kn,Z as An,_ as jn,a as Mn,d as Nn,f as Pn,j as Fn,k as In,m as Ln,o as Rn,u as zn,v as Bn,z as Vn}from"../application-CcrP-v7z.mjs";import{g as Hn,i as Un,r as Wn}from"../service-BzsSm2f6.mjs";import{t as H}from"../multiline-EyzjEwn9.mjs";import{t as Gn}from"../package-json-C690ceex.mjs";import{t as Kn}from"../user-agent-vdHYF3QL.mjs";import{a as qn,i as Jn,n as Yn,o as Xn,r as Zn,t as Qn}from"../errors-BlX4gUw5.mjs";import{t as $n}from"../service_pb-BNxUPfP3.mjs";import{a as er,i as tr,o as nr,r as rr,t as ir}from"../crashreport-BN28xp5B.mjs";import{a as ar,i as or,n as sr}from"../kysely-type-CmvAz1Xj.mjs";import*as U from"pathe";import{dirname as cr,resolve as lr}from"pathe";import{resolvePackageJSON as ur}from"pkg-types";import{arg as W,defineCommand as G,extractFields as dr,runCommand as K,runMain as fr,toCamelCase as pr}from"politty";import{withCompletionCommand as mr}from"politty/completion";import{withSkillCommand as hr}from"politty/skill";import{z as q}from"zod";import{ScalarType as J,create as gr}from"@bufbuild/protobuf";import*as Y from"node:fs";import{accessSync as _r,constants as vr,readdirSync as yr}from"node:fs";import{timestampDate as X}from"@bufbuild/protobuf/wkt";import{pathToFileURL as br}from"node:url";import{generateCodeVerifier as xr}from"@badgateway/oauth2-client";import{Code as Z,ConnectError as Q}from"@connectrpc/connect";import*as Sr from"node:crypto";import{randomBytes as Cr}from"node:crypto";import*as wr from"node:http";import Tr from"open";import*as Er from"rolldown";import{parseSync as Dr}from"oxc-parser";import*as Or from"node:os";import*as $ from"node:fs/promises";import{TraceMap as kr,generatedPositionFor as Ar,originalPositionFor as jr}from"@jridgewell/trace-mapping";import{spawn as Mr,spawnSync as Nr}from"node:child_process";const Pr=$n.methods.filter(e=>e.methodKind===`unary`);function listMethodNames(){return Pr.map(e=>e.name).toSorted()}function listMethodChoices(){return Pr.flatMap(e=>[e.name,`${$n.typeName}/${e.name}`]).toSorted()}function getMethodDescriptor(e){return Pr.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 Fr=new Set([`google.protobuf.Struct`,`google.protobuf.Value`,`google.protobuf.ListValue`,`google.protobuf.NullValue`,`google.protobuf.Any`,`google.protobuf.Empty`]);function isUnrepresentableWellKnownType(e){return Fr.has(e.typeName)}function enumerateAllFieldCompletions(e){let t=getMethodDescriptor(e);if(!t)return[];let n=[],r=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 Ir={[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 Ir[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=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=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 Lr=N({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 Qn({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))}}),Rr=N({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 Error(`Invalid value for bool field: '${t}'. Expected 'true' or 'false'.`)}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 zr=new Set([`__proto__`,`constructor`,`prototype`]),Br=q.string().transform((e,t)=>{let n=e.indexOf(`=`);if(n<0)return t.addIssue({code:q.ZodIssueCode.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:q.ZodIssueCode.custom,message:`Field key cannot be empty`}),q.NEVER;let i=r.split(`.`);if(i.some(e=>e.length===0))return t.addIssue({code:q.ZodIssueCode.custom,message:`Invalid field key: '${r}'. Dotted segments cannot be empty`}),q.NEVER;let a=i.find(e=>zr.has(e));return a?(t.addIssue({code:q.ZodIssueCode.custom,message:`Invalid field key: '${r}'. Segment '${a}' is not allowed.`}),q.NEVER):{path:i,value:e.slice(n+1)}}),Vr=N({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:Rr,inspect:Lr},args:q.strictObject({...F,...ze,body:W(q.string().default(`{}`),{alias:`b`,description:`Request body as JSON.`}),field:W(Br.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 R({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 Error(`--field requires --body to be a JSON object (or omitted).`);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 A({workspaceId:e[`workspace-id`],profile:e.profile}),i=!0}catch{}if(a.includes(`namespaceName`)&&!Object.hasOwn(r,`namespaceName`))try{let{config:n}=await M(e.config),a=resolveNamespaceName(t,n);a&&(r.namespaceName=a,i=!0)}catch{}}let a=await it({profile:e.profile,endpoint:e.endpoint,body:i&&r?JSON.stringify(r):e.body});c.out(JSON.stringify(a.data,null,2))}}),Hr=N({name:`token`,description:`Print a valid Tailor Platform access token to stdout, refreshing it first if expired.`,args:q.strictObject({profile:F.profile}),run:async({profile:e})=>{let t=await C({profile:e});c.out(t)}}),Ur=G({name:`auth`,description:`Authentication helpers for scripts and plugins.`,subCommands:{token:Hr}}),Wr={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 Error(`Failed to fetch OIDC discovery from ${t}: ${qn(e).message}`,{cause:e})});if(!n.ok)throw Error(`Failed to fetch OIDC discovery from ${t}: ${n.status}`);return n.json()}function randomState$1(){return Sr.randomBytes(32).toString(`base64url`)}const Gr=N({name:`authorize`,description:`Authorize an auth connection via OAuth2 flow.`,args:q.strictObject({...F,...Wr,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 R({profile:e.profile});let t=await C({profile:e.profile}),n=await B(t),r=await A({workspaceId:e[`workspace-id`],profile:e.profile}),i=(await Dn(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 Error(`Auth connection "${e.name}" not found.`);if(i.config.case!==`oauth2`)throw Error(`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((t,i)=>{let handleCallback=async(c,l)=>{if(!c.url?.startsWith(`/callback`)){l.writeHead(404),l.end(`Not found`);return}try{let i=new URL(c.url,`http://localhost:${e.port}`),u=i.searchParams.get(`code`),d=i.searchParams.get(`state`),f=i.searchParams.get(`error`);if(f)throw Error(`Authorization failed: ${f}`);if(d!==s)throw Error(`State mismatch — possible CSRF attack.`);if(!u)throw Error(`No authorization code received.`);await n.exchangeAuthConnectionAuthorizationCode({workspaceId:r,connectionName:e.name,authorizationCode:u,redirectUri:o}),l.writeHead(200,{"Content-Type":`text/html`}),l.end(`<html><body><h1>Authorization successful</h1><p>You can close this window.</p></body></html>`),a.close(),t()}catch(e){l.writeHead(400,{"Content-Type":`text/plain`}),l.end(`Authorization failed: ${e instanceof Error?e.message:`Unknown error`}`),a.close(),i(qn(e))}},a=wr.createServer((e,t)=>void handleCallback(e,t)),l=setTimeout(()=>{a.close(),i(Error(`Authorization timeout exceeded (5 minutes).`))},3e5);a.on(`close`,()=>{clearTimeout(l)}),a.on(`error`,t=>{clearTimeout(l);let n=t.code,r=n===`EADDRINUSE`||n===`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}${n?` (${n})`:``}.\n${r}\n tailor authconnection open`),i(t)});let announceAuthorizeUrl=async()=>{let t=u.toString();if(c.info(e[`no-browser`]?`Open this URL in your browser to authorize:\n\n${t}\n`:`Opening browser for authorization:\n\n${t}\n`),c.info(`If this flow doesn't complete, you can authorize via the Console instead:
4
- tailor authconnection open`),!e[`no-browser`])try{await Tr(t)}catch{c.warn(`Failed to open browser automatically. Please open the URL above manually.`)}};a.listen(e.port,()=>void announceAuthorizeUrl())}),c.success(`Auth connection "${e.name}" authorized successfully.`)}}),Kr=N({name:`delete`,description:`Delete an auth connection entirely.`,args:q.strictObject({...F,...Wr,...O}),run:async e=>{await R({profile:e.profile});let t=await C({profile:e.profile}),n=await B(t),r=await A({workspaceId:e[`workspace-id`],profile:e.profile});if(!e.yes&&await z.text({message:`Enter the connection name to confirm deletion ("${e.name}"):`})!==e.name){c.info(`Auth connection deletion cancelled.`);return}try{await n.deleteAuthConnection({workspaceId:r,connectionName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?Error(`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 qr=N({name:`list`,description:`List all auth connections.`,args:q.strictObject({...F,...Ye()}),run:async e=>{let t=await C({profile:e.profile}),n=await B(t),r=await A({workspaceId:e[`workspace-id`],profile:e.profile});try{let t=f(e.order),i=await V(async(e,i)=>{let{connections:a,nextPageToken:o}=await n.listAuthConnections({workspaceId:r,pageToken:e,pageSize:i,pageDirection:t});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}}}),Jr=N({name:`open`,description:`Open the auth connections page in the Tailor Platform Console.`,args:q.strictObject({...F}),run:async e=>{let t=await A({workspaceId:e[`workspace-id`],profile:e.profile}),n=s(process.env.TAILOR_CONSOLE_NEXT)===!0?`/workspaces/${t}/services/auth-connections`:`/workspaces/${t}/settings/connections`,r=await Et({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 Tr(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}`)}}),Yr=N({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({...F,...Wr,...O}),run:async e=>{await R({profile:e.profile});let t=await C({profile:e.profile}),n=await B(t),r=await A({workspaceId:e[`workspace-id`],profile:e.profile});if(!e.yes&&await z.text({message:`Enter the connection name to confirm revocation ("${e.name}"):`})!==e.name){c.info(`Auth connection revocation cancelled.`);return}try{await n.revokeAuthConnection({workspaceId:r,connectionName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?Error(`Auth connection "${e.name}" not found.`,{cause:t}):t}c.success(`Auth connection "${e.name}" revoked.`)}}),Xr=G({name:`authconnection`,description:`Manage auth connections.`,subCommands:{authorize:Gr,list:qr,open:Jr,revoke:Yr,delete:Kr},async run(){await K(qr,[])}});function orderAndLimitCrashReports(e,t){let n=e.filter(e=>e.endsWith(tr)).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:U.join(t,e)}))}const Zr=N({name:`list`,description:`List local crash report files.`,args:q.strictObject({...Ye()}),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}`)}}),Qr=N({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 Kn();c.info(`Sending crash report...`),await rr(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,`
5
- `),n=`\n${er}\n`,r=t.lastIndexOf(n);if(r===-1)return;let i=t.slice(r+n.length).split(`
6
- `)[0];return i?JSON.parse(i):void 0}catch{return}}const $r=G({name:`crashreport`,description:`Manage crash reports.`,subCommands:{list:Zr,send:Qr},async run(){await K(Zr,[])}}),ei=N({name:`deploy`,description:`Deploy your application by applying the Tailor configuration.`,args:q.strictObject({...F,...Ge,...O,"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 R({profile:e.profile});let{initTelemetry:t}=await import(`../telemetry-DXHP3VVi.mjs`);await t(),await p({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})}}),ti=G({name:`executor`,description:`Manage executors`,subCommands:{trigger:be,jobs:mn,list:ne,get:Ue,webhook:_e},async run(){await K(ne,[])}});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 ni=/^\s+at\s+(?:(.+?)\s+\()?(file:\/\/\/.+?):(\d+):(\d+)\)?$/;function parseStackTrace(e){let t=e.split(`
2
+ import{r as e}from"../schema-6d_OHyZf.mjs";import{E as t,Ft as n,Ht as r,Ot as i,q as a}from"../workspace_resource_pb-u9bj6p3i.mjs";import{t as o}from"../assert-WeXvmG4j.mjs";import{a as s,n as c,r as l}from"../logger-CCjs1DuH.mjs";import{$ as u,$n as d,$r as f,$t as p,An as m,Ar as h,B as g,Br as _,C as v,Cn as y,Cr as b,Ct as x,Dn as ee,Dr as S,Dt as C,E as te,En as ne,Er as re,Fn as ie,Fr as ae,Ft as oe,Gn as se,Gr as w,Hr as ce,Ht as le,I as ue,In as de,Ir as fe,Jn as pe,Jr as me,K as he,Kt as ge,L as _e,Ln as T,Lr as ve,M as ye,Mn as be,Mr as xe,Mt as Se,N as Ce,Nn as we,Nr as Te,Nt as Ee,O as De,On as Oe,Or as ke,P as Ae,Pn as je,Pr as Me,R as Ne,Rn as E,Rr as Pe,Sn as Fe,Sr as D,St as Ie,Tn as Le,Tr as O,Tt as Re,Ur as ze,V as Be,Vr as Ve,W as He,Wn as Ue,Wr as k,Wt as We,X as Ge,Xn as Ke,Xt as qe,Yr as A,Yt as Je,Z as Ye,Zn as Xe,Zr as j,_n as Ze,_r as Qe,_t as $e,a as et,an as tt,ar as nt,at as rt,bn as it,br as at,bt as ot,c as st,cn as ct,cr as lt,dr as ut,dt,ei as ft,en as pt,er as mt,f as ht,fn as gt,fr as _t,g as vt,gn as yt,gr as M,gt as bt,hn as xt,hr as St,ii as N,in as Ct,ir as wt,j as Tt,jn as Et,jr as Dt,kn as P,kr as Ot,kt,ln as At,lr as jt,lt as Mt,m as Nt,mn as Pt,mr as Ft,ni as It,nn as Lt,nr as Rt,o as zt,or as Bt,pr as Vt,pt as Ht,q as Ut,qn as Wt,qr as Gt,r as Kt,ri as F,rr as qt,rt as Jt,sn as Yt,sr as Xt,st as Zt,t as Qt,ti as I,tn as $t,tr as en,tt as tn,u as nn,ur as L,v as rn,vn as an,vr as on,w as sn,wn as cn,wr as R,wt as ln,x as un,xn as dn,xr as z,xt as fn,yn as pn,yr as mn,yt as hn,z as gn,zr as B,zt as _n}from"../register-ts-hook-CoZS-8Mx.mjs";import{$ as vn,A as yn,B as bn,D as xn,E as Sn,G as Cn,H as wn,J as Tn,K as En,M as Dn,O as On,Q as kn,T as An,V as jn,W as V,X as Mn,Y as Nn,Z as Pn,_ as Fn,a as In,d as Ln,f as Rn,j as zn,k as Bn,m as Vn,o as Hn,u as Un,v as Wn,z as Gn}from"../application-D3HlhR3i.mjs";import{g as Kn,i as qn,r as Jn}from"../service-BzsSm2f6.mjs";import{t as H}from"../multiline-EyzjEwn9.mjs";import{t as Yn}from"../package-json-C690ceex.mjs";import{t as Xn}from"../user-agent-vdHYF3QL.mjs";import{a as Zn,i as Qn,n as $n,o as er,r as tr,t as nr}from"../errors-BlX4gUw5.mjs";import{t as rr}from"../service_pb-CxHztLk1.mjs";import{a as ir,i as ar,o as or,r as sr,t as cr}from"../crashreport-BN28xp5B.mjs";import{a as lr,i as ur,n as dr}from"../kysely-type-B-BOlXH7.mjs";import*as U from"pathe";import{dirname as fr,resolve as pr}from"pathe";import{resolvePackageJSON as mr}from"pkg-types";import{arg as W,defineCommand as G,extractFields as hr,runCommand as K,runMain as gr,toCamelCase as _r}from"politty";import{withCompletionCommand as vr}from"politty/completion";import{withSkillCommand as yr}from"politty/skill";import{z as q}from"zod";import{ScalarType as J,create as br}from"@bufbuild/protobuf";import*as Y from"node:fs";import{accessSync as xr,constants as Sr,readdirSync as Cr}from"node:fs";import{timestampDate as X}from"@bufbuild/protobuf/wkt";import{pathToFileURL as wr}from"node:url";import{generateCodeVerifier as Tr}from"@badgateway/oauth2-client";import{Code as Z,ConnectError as Q}from"@connectrpc/connect";import*as Er from"node:crypto";import{randomBytes as Dr}from"node:crypto";import*as Or from"node:http";import kr from"open";import*as Ar from"rolldown";import{parseSync as jr}from"oxc-parser";import*as Mr from"node:os";import*as $ from"node:fs/promises";import{TraceMap as Nr,generatedPositionFor as Pr,originalPositionFor as Fr}from"@jridgewell/trace-mapping";import{spawn as Ir,spawnSync as Lr}from"node:child_process";const Rr=rr.methods.filter(e=>e.methodKind===`unary`);function listMethodNames(){return Rr.map(e=>e.name).toSorted()}function listMethodChoices(){return Rr.flatMap(e=>[e.name,`${rr.typeName}/${e.name}`]).toSorted()}function getMethodDescriptor(e){return Rr.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 zr=new Set([`google.protobuf.Struct`,`google.protobuf.Value`,`google.protobuf.ListValue`,`google.protobuf.NullValue`,`google.protobuf.Any`,`google.protobuf.Empty`]);function isUnrepresentableWellKnownType(e){return zr.has(e.typeName)}function enumerateAllFieldCompletions(e){let t=getMethodDescriptor(e);if(!t)return[];let n=[],r=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 Br={[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 Br[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=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=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 Vr=w({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 nr({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))}}),Hr=w({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 Error(`Invalid value for bool field: '${t}'. Expected 'true' or 'false'.`)}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 Ur=new Set([`__proto__`,`constructor`,`prototype`]),Wr=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=>Ur.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)}}),Gr=w({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:Hr,inspect:Vr},args:q.strictObject({...N,...me,body:W(q.string().default(`{}`),{alias:`b`,description:`Request body as JSON.`}),field:W(Wr.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 R({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 Error(`--field requires --body to be a JSON object (or omitted).`);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 ve({workspaceId:e[`workspace-id`],profile:e.profile}),i=!0}catch{}if(a.includes(`namespaceName`)&&!Object.hasOwn(r,`namespaceName`))try{let{config:n}=await O(e.config),a=resolveNamespaceName(t,n);a&&(r.namespaceName=a,i=!0)}catch{}}let a=await b({profile:e.profile,endpoint:e.endpoint,body:i&&r?JSON.stringify(r):e.body});c.out(JSON.stringify(a.data,null,2))}}),Kr=w({name:`status`,description:`Show the active Tailor Platform authentication status without printing tokens.`,args:q.strictObject({profile:N.profile}),run:async({profile:e})=>{let t=await Dt({profile:e});if(c.out(t),!t.authenticated)throw Error(`Not authenticated. Run 'tailor login' and try again.`)}}),qr=w({name:`token`,description:`Print a valid Tailor Platform access token to stdout, refreshing it first if expired.`,args:q.strictObject({profile:N.profile}),run:async({profile:e})=>{let t=await h({profile:e});c.out(t)}}),Jr=G({name:`auth`,description:`Authentication helpers for scripts and plugins.`,subCommands:{status:Kr,token:qr}}),Yr={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 Error(`Failed to fetch OIDC discovery from ${t}: ${Zn(e).message}`,{cause:e})});if(!n.ok)throw Error(`Failed to fetch OIDC discovery from ${t}: ${n.status}`);return n.json()}function randomState$1(){return Er.randomBytes(32).toString(`base64url`)}const Xr=w({name:`authorize`,description:`Authorize an auth connection via OAuth2 flow.`,args:q.strictObject({...N,...Yr,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 R({profile:e.profile});let{client:t,workspaceId:n}=await D({profile:e.profile,workspaceId:e[`workspace-id`]}),r=(await jn(async(e,r)=>{let{connections:i,nextPageToken:a}=await t.listAuthConnections({workspaceId:n,pageToken:e,pageSize:r});return[i,a]})).find(t=>t.name===e.name);if(!r)throw Error(`Auth connection "${e.name}" not found.`);if(r.config.case!==`oauth2`)throw Error(`Auth connection "${e.name}" is not an OAuth2 connection.`);let i=r.config.value,a=`http://localhost:${e.port}/callback`,o=randomState$1(),s;s=i.authUrl?i.authUrl:(await fetchOIDCDiscovery(i.providerUrl)).authorization_endpoint;let l=new URL(s);l.searchParams.set(`client_id`,i.clientId),l.searchParams.set(`redirect_uri`,a),l.searchParams.set(`response_type`,`code`),l.searchParams.set(`scope`,e.scopes.replace(/,/g,` `)),l.searchParams.set(`state`,o),l.searchParams.set(`access_type`,`offline`),await new Promise((r,i)=>{let handleCallback=async(c,l)=>{if(!c.url?.startsWith(`/callback`)){l.writeHead(404),l.end(`Not found`);return}try{let i=new URL(c.url,`http://localhost:${e.port}`),u=i.searchParams.get(`code`),d=i.searchParams.get(`state`),f=i.searchParams.get(`error`);if(f)throw Error(`Authorization failed: ${f}`);if(d!==o)throw Error(`State mismatch — possible CSRF attack.`);if(!u)throw Error(`No authorization code received.`);await t.exchangeAuthConnectionAuthorizationCode({workspaceId:n,connectionName:e.name,authorizationCode:u,redirectUri:a}),l.writeHead(200,{"Content-Type":`text/html`}),l.end(`<html><body><h1>Authorization successful</h1><p>You can close this window.</p></body></html>`),s.close(),r()}catch(e){l.writeHead(400,{"Content-Type":`text/plain`}),l.end(`Authorization failed: ${e instanceof Error?e.message:`Unknown error`}`),s.close(),i(Zn(e))}},s=Or.createServer((e,t)=>void handleCallback(e,t)),u=setTimeout(()=>{s.close(),i(Error(`Authorization timeout exceeded (5 minutes).`))},3e5);s.on(`close`,()=>{clearTimeout(u)}),s.on(`error`,t=>{clearTimeout(u);let n=t.code,r=n===`EADDRINUSE`||n===`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}${n?` (${n})`:``}.\n${r}\n tailor authconnection open`),i(t)});let announceAuthorizeUrl=async()=>{let t=l.toString();if(c.info(e[`no-browser`]?`Open this URL in your browser to authorize:\n\n${t}\n`:`Opening browser for authorization:\n\n${t}\n`),c.info(`If this flow doesn't complete, you can authorize via the Console instead:
4
+ tailor authconnection open`),!e[`no-browser`])try{await kr(t)}catch{c.warn(`Failed to open browser automatically. Please open the URL above manually.`)}};s.listen(e.port,()=>void announceAuthorizeUrl())}),c.success(`Auth connection "${e.name}" authorized successfully.`)}}),Zr=w({name:`delete`,description:`Delete an auth connection entirely.`,args:q.strictObject({...N,...Yr,...A}),run:async e=>{await R({profile:e.profile});let{client:t,workspaceId:n}=await D({profile:e.profile,workspaceId:e[`workspace-id`]});if(!e.yes&&await z.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?Error(`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 Qr=w({name:`list`,description:`List all auth connections.`,args:q.strictObject({...N,...I()}),run:async e=>{let{client:t,workspaceId:n}=await D({profile:e.profile,workspaceId:e[`workspace-id`]});try{let r=F(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}}}),$r=w({name:`open`,description:`Open the auth connections page in the Tailor Platform Console.`,args:q.strictObject({...N}),run:async e=>{let t=await ve({workspaceId:e[`workspace-id`],profile:e.profile}),n=s(process.env.TAILOR_CONSOLE_NEXT)===!0?`/workspaces/${t}/services/auth-connections`:`/workspaces/${t}/settings/connections`,r=await Te({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 kr(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}`)}}),ei=w({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({...N,...Yr,...A}),run:async e=>{await R({profile:e.profile});let{client:t,workspaceId:n}=await D({profile:e.profile,workspaceId:e[`workspace-id`]});if(!e.yes&&await z.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?Error(`Auth connection "${e.name}" not found.`,{cause:t}):t}c.success(`Auth connection "${e.name}" revoked.`)}}),ti=G({name:`authconnection`,description:`Manage auth connections.`,subCommands:{authorize:Xr,list:Qr,open:$r,revoke:ei,delete:Zr},async run(){await K(Qr,[])}});function orderAndLimitCrashReports(e,t){let n=e.filter(e=>e.endsWith(ar)).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:U.join(t,e)}))}const ni=w({name:`list`,description:`List local crash report files.`,args:q.strictObject({...I()}),run:async e=>{let t=or(),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}`)}}),ri=w({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 Xn();c.info(`Sending crash report...`),await sr(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,`
5
+ `),n=`\n${ir}\n`,r=t.lastIndexOf(n);if(r===-1)return;let i=t.slice(r+n.length).split(`
6
+ `)[0];return i?JSON.parse(i):void 0}catch{return}}const ii=G({name:`crashreport`,description:`Manage crash reports.`,subCommands:{list:ni,send:ri},async run(){await K(ni,[])}}),ai=w({name:`deploy`,description:`Deploy your application by applying the Tailor configuration.`,args:q.strictObject({...N,...f,...A,"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 R({profile:e.profile});let{initTelemetry:t}=await import(`../telemetry-DXHP3VVi.mjs`);await t(),await p({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})}}),oi=G({name:`executor`,description:`Manage executors`,subCommands:{trigger:Ee,jobs:_n,list:oe,get:qe,webhook:Se},async run(){await K(oe,[])}});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 si=/^\s+at\s+(?:(.+?)\s+\()?(file:\/\/\/.+?):(\d+):(\d+)\)?$/;function parseStackTrace(e){let t=e.split(`
7
7
  `),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(`
8
- `);i.startsWith(`rpc error: code = Aborted desc = `)&&(i=i.slice(33));let a=[];for(let e of r){let t=ni.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 ri=/\/\/[#@]\s*sourceMappingURL=data:application\/json[^,]*;base64,(.+)$/m;function extractInlineSourcemap(e){let t=ri.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 kr(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=Ar(t,{source:r,line:e.line,column:e.column-1});if(i.line==null)continue;let a=jr(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
+ `);i.startsWith(`rpc error: code = Aborted desc = `)&&(i=i.slice(33));let a=[];for(let e of r){let t=si.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 ci=/\/\/[#@]\s*sourceMappingURL=data:application\/json[^,]*;base64,(.+)$/m;function extractInlineSourcemap(e){let t=ci.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 Nr(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=Pr(t,{source:r,line:e.line,column:e.column-1});if(i.line==null)continue;let a=Fr(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(`
9
9
  `),r=Math.max(0,t-1-2),i=Math.min(n.length,t+2),a=String(i).length,o=[];for(let e=r;e<i;e++){let r=e+1,i=String(r).padStart(a),s=n[e];r===t?o.push(` ${l.error(`>`)} ${l.error(`${i} | ${s}`)}`):o.push(` ${l.dim(`${i} | ${s}`)}`)}return o.join(`
10
10
  `)}function formatMappedError(e,t,n,r){let i=[` ${l.error(e)}`];for(let e of t)if(e.mapped){let{source:t,line:a,column:o,name:s}=e.mapped,c=r?U.resolve(r,t):U.resolve(t),l=U.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 ${l.dim(`at ${e.original.functionName} (${t})`)}`)}return i.join(`
11
- `)}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:Ke(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,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
+ `)}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:Je(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,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(`
12
12
  `,1)[0]??``;return/^\s+at\s+/.test(i)?`${t}: ${n}\n${r}`:r}function formatExecutionErrorFallback(e){let[t=``,...n]=composeExecutionErrorString(e).split(`
13
13
  `);return[` ${l.error(t)}`,...n.map(e=>` ${l.dim(e)}`)].join(`
14
- `)}function formatExecutionError(e,t){if(t&&e.stackTrace){let n=formatErrorWithSourcemap(composeExecutionErrorString(e),t,process.cwd());if(n)return n}return formatExecutionErrorFallback(e)}function printFunctionExecutionDetail(e){let{detail:t,bundledCode:n}=e,formatDate=e=>e?e.toISOString():`N/A`,r=[[`id`,t.id],[`scriptName`,t.scriptName],[`status`,t.status],[`type`,t.type],[`startedAt`,formatDate(t.startedAt)],[`finishedAt`,formatDate(t.finishedAt)]];if(c.out(Ut(r)),t.logs){c.log(l.bold(`
14
+ `)}function formatExecutionError(e,t){if(t&&e.stackTrace){let n=formatErrorWithSourcemap(composeExecutionErrorString(e),t,process.cwd());if(n)return n}return formatExecutionErrorFallback(e)}function printFunctionExecutionDetail(e){let{detail:t,bundledCode:n}=e,formatDate=e=>e?e.toISOString():`N/A`,r=[[`id`,t.id],[`scriptName`,t.scriptName],[`status`,t.status],[`type`,t.type],[`startedAt`,formatDate(t.startedAt)],[`finishedAt`,formatDate(t.finishedAt)]];if(c.out(Yt(r)),t.logs){c.log(l.bold(`
15
15
  Logs:`));for(let e of t.logs.split(`
16
16
  `))c.log(` ${e}`)}if(t.result){c.log(l.bold(`
17
17
  Result:`));try{let e=JSON.parse(t.result);c.log(` ${JSON.stringify(e,null,2).split(`
18
18
  `).join(`
19
19
  `)}`)}catch{c.log(` ${t.result}`)}}t.error&&(c.log(l.bold(`
20
- Error:`)),c.log(formatExecutionError(t.error,n??null)))}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 ii=N({name:`logs`,description:`List or get function execution logs.`,notes:`When 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).
20
+ Error:`)),c.log(formatExecutionError(t.error,n??null)))}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 li=w({name:`logs`,description:`List or get function execution logs.`,notes:`When 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).
21
21
 
22
- Stack 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`}],args:q.strictObject({...F,...He,"execution-id":W(q.string().optional(),{positional:!0,description:`Execution ID (if provided, shows details with logs)`})}),run:async e=>{let t=await C({profile:e.profile}),n=await B(t),r=await A({workspaceId:e[`workspace-id`],profile:e.profile});if(e.executionId){let{execution:t}=await n.getFunctionExecution({workspaceId:r,executionId:e.executionId});if(!t)throw Error(`Function execution '${e.executionId}' not found.`);let i=toFunctionExecutionDetailInfo(t);e.json?c.out(i):printFunctionExecutionDetail({detail:i,bundledCode:i.error?await downloadScriptForMapping({client:n,workspaceId:r,scriptName:i.scriptName,executionType:t.type,executionContentHash:t.contentHash}):null})}else{let t=f(e.order),i=(await V(async(e,i)=>{let{executions:a,nextPageToken:o}=await n.listFunctionExecutions({workspaceId:r,pageToken:e,pageSize:i,pageDirection:t});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=Mn(e.inlineSourcemap),c=Fn(e.logLevel),l=U.resolve(Rn(),`test-run`);Y.mkdirSync(l,{recursive:!0});let u=`test-run--${t.name}`,d=`${u}.js`,f=U.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 vn(r),h=wn({tsconfig:m}),g=await Er.build({plugins:[En(f,r),yn(),Tn],input:f,write:!1,output:{format:`esm`,sourcemap:!s||`inline`,minify:!s||{mangle:{keepNames:!0}},codeSplitting:!1,dir:process.cwd()},tsconfig:m,treeshake:In([gn(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=U.resolve(n);switch(t.type){case`plain`:return t.namedMain?H`
22
+ Stack 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`}],args:q.strictObject({...N,...ft,"execution-id":W(q.string().optional(),{positional:!0,description:`Execution ID (if provided, shows details with logs)`})}),run:async e=>{let{client:t,workspaceId:n}=await D({profile:e.profile,workspaceId:e[`workspace-id`]});if(e.executionId){let{execution:r}=await t.getFunctionExecution({workspaceId:n,executionId:e.executionId});if(!r)throw Error(`Function execution '${e.executionId}' not found.`);let i=toFunctionExecutionDetailInfo(r);e.json?c.out(i):printFunctionExecutionDetail({detail:i,bundledCode:i.error?await downloadScriptForMapping({client:t,workspaceId:n,scriptName:i.scriptName,executionType:r.type,executionContentHash:r.contentHash}):null})}else{let r=F(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=In(e.inlineSourcemap),c=zn(e.logLevel),l=U.resolve(Hn(),`test-run`);Y.mkdirSync(l,{recursive:!0});let u=`test-run--${t.name}`,d=`${u}.js`,f=U.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 xn(r),h=Dn({tsconfig:m}),g=await Ar.build({plugins:[An(f,r),Sn(),On],input:f,write:!1,output:{format:`esm`,sourcemap:!s||`inline`,minify:!s||{mangle:{keepNames:!0}},codeSplitting:!1,dir:process.cwd()},tsconfig:m,treeshake:Bn([yn(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=U.resolve(n);switch(t.type){case`plain`:return t.namedMain?H`
23
23
  export { main } from "${c}";
24
24
  `:H`
25
25
  import _fn from "${c}";
26
26
  export { _fn as main };
27
- `;case`resolver`:{let e=buildMachinePrincipalExpr(i,a),n=jn({permission:t.permission,defaultPermission:s});return H`
27
+ `;case`resolver`:{let e=buildMachinePrincipalExpr(i,a),n=Fn({permission:t.permission,defaultPermission:s});return H`
28
28
  import _internalResolver from "${c}";
29
29
  import { t } from "@tailor-platform/sdk";
30
30
 
31
31
  const $tailor_resolver_body = async (rawInput) => {
32
32
  const _caller = ${e};
33
- const invoker = (${Ln}) ?? _caller;
33
+ const invoker = (${Vn}) ?? _caller;
34
34
  const context = { input: rawInput, env: ${JSON.stringify(r)}, caller: _caller, invoker };
35
35
  ${n}
36
36
  return _internalResolver.body(context);
@@ -44,7 +44,7 @@ Stack traces are mapped only when the execution includes a content hash for the
44
44
  const _actor = ${e};
45
45
 
46
46
  const __executor_function = async (args) => {
47
- const _invoker = ${Ln} ?? _actor;
47
+ const _invoker = ${Vn} ?? _actor;
48
48
  return _internalExecutor.operation.body({ ...args, env: _env, actor: _actor, invoker: _invoker });
49
49
  };
50
50
 
@@ -56,52 +56,52 @@ Stack traces are mapped only when the execution includes a content hash for the
56
56
  const fallbackInvoker = ${n};
57
57
 
58
58
  export async function main(input) {
59
- const invoker = ${Ln} ?? fallbackInvoker;
59
+ const invoker = ${Vn} ?? fallbackInvoker;
60
60
  return await ${e}.body(input, { env, invoker });
61
61
  }
62
- `}}}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(br(n).href),a=Pn.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}}let o=Un.safeParse(Wn(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 Error(`Could not detect function type from ${n}.\nThe file must have one of:
62
+ `}}}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(wr(n).href),a=Rn.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}}let o=qn.safeParse(Jn(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 Error(`Could not detect function type from ${n}.\nThe file must have one of:
63
63
  - A default-exported resolver (createResolver)
64
64
  - A default-exported executor (createExecutor) with function/jobFunction operation
65
65
  - A named-exported workflow job (createWorkflowJob)
66
66
  - A default-exported function
67
- - 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=zn.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
+ - 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=Un.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(`
68
68
  `);throw Error(`Workflow job "${t}" not found. 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(`
69
- `);throw Error(`Multiple workflow jobs found. Specify one with --name:\n${r}`)}function deriveNameFromPath(e){return U.basename(e,U.extname(e))}const ai=`db.ts`,oi=`db.snapshot.json`,si=[`/**`,` * 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(`
70
- `);function generateScriptDbTypes(e){let t=Object.values(e.tables).map(e=>ar(e.name,e.fields)),n=t.reduce((e,t)=>({Timestamp:e.Timestamp||t.usedUtilityTypes.Timestamp,Serial:e.Serial||t.usedUtilityTypes.Serial}),{Timestamp:!1,Serial:!1}),r=or([{namespace:e.namespace,types:t,usedUtilityTypes:n}]);return`${si}\n\n${r}`}function isGeneratedScriptDbTypes(e){return e.includes("Generated by `tailor function script`")}function assertGeneratedTypeScript(e,t){let{errors:n}=Dr(U.basename(e),t);if(n.length>0)throw Error(`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(`
71
- `)}function loadScriptSchemaSnapshot(e){let t=U.join(U.dirname(e),oi);if(!Y.existsSync(t))return null;let n;try{n=JSON.parse(Y.readFileSync(t,`utf-8`))}catch(e){throw Error(`Failed to parse schema snapshot ${t}: ${e instanceof Error?e.message:e}. 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:Wt(a)}}catch{throw unexpectedSnapshotShapeError(t)}}function unexpectedSnapshotShapeError(e){return Error(`Schema snapshot ${e} has an unexpected shape. 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(on(r).includes(s)){let{namespaces:t}=await je({configPath:i,namespaces:[s]}),n=t[0];if(n){let t=Object.fromEntries(Object.values(n.tables).map(e=>[e.name,Te(e)])),r=tt(generatedContractSnapshot(o),generatedContractSnapshot({...o,tables:t}));if(pt(r))throw schemaDriftError(`the local table definitions`,r,e)}}let c=await It(t,n,s),l=tt(a.source===`local`?generatedContractSnapshot(o):Wt(pickTableFields(o)),a.source===`local`?generatedContractSnapshot(c):Wt(pickTableFields(c)));if(pt(l))throw schemaDriftError(`the deployed schema`,l,e)}function fieldsOnlySnapshot(e){return Wt(pickTableFields(Ct(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 Wt({...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=Yn([`tailor`,`function`,`script`,n.scriptArgValue,...n.sidecar.source===`remote`?[`--remote`]:[],...r]),a=Yn([`tailor`,`function`,`run`,n.scriptArgValue,`--allow-schema-drift`,...r]);return Error(`Schema drift detected: ${oi} next to the script no longer matches ${e}.\n\n${st(t)}\n\nRefresh the generated types with ${i}, or run anyway with ${a}.`)}const ci=N({name:`run`,aliases:[`test-run`],description:`Run a function on the Tailor Platform server without deploying.`,args:q.object({...F,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=U.resolve(e.file);if(!Y.existsSync(n))throw Error(`File not found: ${n}`);let{config:r}=await M(e.config),a=resolveAuthNamespace(r.auth),o=await resolveMachineUserName({cliMachineUser:e[`machine-user`],cliMachineUserSource:De(e[`machine-user`]),profile:e.profile,authConfig:r.auth}),s=await C({profile:e.profile}),u=await B(s),d=await A({workspaceId:e[`workspace-id`],profile:e.profile}),f=await resolveMachineUser({client:u,workspaceId:d,authNamespace:a,machineUserName:o,authConfig:r.auth}),p=U.relative(process.cwd(),n),m=n.endsWith(`.js`);if(!m){if(e[`allow-schema-drift`])Y.existsSync(U.join(U.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:u,workspaceId:d,config:r,configArgValue:e.config,scriptArgValue:e.file,profileArgValue:e.profile,sidecar:t}))}}let h,g,_,v;if(m)g=U.basename(n),h=Y.readFileSync(n,`utf-8`),c.info(`Using pre-bundled script ${l.bold(g)}`);else{c.info(`Detecting function type from ${l.path(p)}`);let t=await detectFunctionType({filePath:n,jobName:e.name});_=t.type,v=t.name,c.info(`Detected: ${l.bold(t.type)} ${l.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=U.dirname(r.path);({bundledCode:h,scriptName:g}=await bundleForRun({detected:t,sourceFile:n,baseDir:i,defaultPermission:t.type===`resolver`?Nn({config:r.resolver,filePath:n,baseDir:i}):void 0,env:r.env??{},inlineSourcemap:r.inlineSourcemap,logLevel:r.logLevel,machineUser:f,workspaceId:d})),c.info(`Bundled as ${l.bold(g)}`)}let y=gr(i,{namespace:a,machineUserName:f.name});c.info(`Executing on workspace ${l.dim(d)}...`);let b;if(e.arg!==void 0)try{b=JSON.parse(e.arg)}catch(e){throw Error(`Invalid --arg JSON: ${e instanceof Error?e.message:e}`,{cause:e})}let x=await Pe({client:u,workspaceId:d,name:g,code:h,arg:b,invoker:y});if(t)c.out({success:x.success,scriptName:g,functionType:_,functionName:v,logs:x.logs,result:x.result,error:x.error});else{if(x.success?c.success(`Execution succeeded`):c.error(`Execution failed`),x.logs.trim()){c.log(l.bold(`
72
- Logs:`));for(let e of x.logs.split(`
73
- `))c.log(` ${e}`)}if(x.result&&x.success){c.log(l.bold(`
74
- Result:`));try{let e=JSON.parse(x.result);c.log(` ${JSON.stringify(e,null,2).split(`
69
+ `);throw Error(`Multiple workflow jobs found. Specify one with --name:\n${r}`)}function deriveNameFromPath(e){return U.basename(e,U.extname(e))}const ui=`db.ts`,di=`db.snapshot.json`,fi=[`/**`,` * 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(`
70
+ `);function generateScriptDbTypes(e){let t=Object.values(e.tables).map(e=>lr(e.name,e.fields)),n=ur([{namespace:e.namespace,types:t}]);return`${fi}\n\n${n}`}function isGeneratedScriptDbTypes(e){return e.includes("Generated by `tailor function script`")}function assertGeneratedTypeScript(e,t){let{errors:n}=jr(U.basename(e),t);if(n.length>0)throw Error(`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(`
71
+ `)}function loadScriptSchemaSnapshot(e){let t=U.join(U.dirname(e),di);if(!Y.existsSync(t))return null;let n;try{n=JSON.parse(Y.readFileSync(t,`utf-8`))}catch(e){throw Error(`Failed to parse schema snapshot ${t}: ${e instanceof Error?e.message:e}. 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:jt(a)}}catch{throw unexpectedSnapshotShapeError(t)}}function unexpectedSnapshotShapeError(e){return Error(`Schema snapshot ${e} has an unexpected shape. 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(ln(r).includes(s)){let{namespaces:t}=await Ie({configPath:i,namespaces:[s]}),n=t[0];if(n){let t=Object.fromEntries(Object.values(n.tables).map(e=>[e.name,de(e)])),r=Xt(generatedContractSnapshot(o),generatedContractSnapshot({...o,tables:t}));if(Ft(r))throw schemaDriftError(`the local table definitions`,r,e)}}let c=await xt(t,n,s),l=Xt(a.source===`local`?generatedContractSnapshot(o):jt(pickTableFields(o)),a.source===`local`?generatedContractSnapshot(c):jt(pickTableFields(c)));if(Ft(l))throw schemaDriftError(`the deployed schema`,l,e)}function fieldsOnlySnapshot(e){return jt(pickTableFields(we(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 jt({...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=$n([`tailor`,`function`,`script`,n.scriptArgValue,...n.sidecar.source===`remote`?[`--remote`]:[],...r]),a=$n([`tailor`,`function`,`run`,n.scriptArgValue,`--allow-schema-drift`,...r]);return Error(`Schema drift detected: ${di} next to the script no longer matches ${e}.\n\n${Vt(t)}\n\nRefresh the generated types with ${i}, or run anyway with ${a}.`)}const pi=w({name:`run`,aliases:[`test-run`],description:`Run a function on the Tailor Platform server without deploying.`,args:q.object({...N,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=U.resolve(e.file);if(!Y.existsSync(n))throw Error(`File not found: ${n}`);let{config:r}=await O(e.config),a=resolveAuthNamespace(r.auth),o=await resolveMachineUserName({cliMachineUser:e[`machine-user`],cliMachineUserSource:It(e[`machine-user`]),profile:e.profile,authConfig:r.auth}),{client:s,workspaceId:u}=await D({profile:e.profile,workspaceId:e[`workspace-id`]}),d=await resolveMachineUser({client:s,workspaceId:u,authNamespace:a,machineUserName:o,authConfig:r.auth}),f=U.relative(process.cwd(),n),p=n.endsWith(`.js`);if(!p){if(e[`allow-schema-drift`])Y.existsSync(U.join(U.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:s,workspaceId:u,config:r,configArgValue:e.config,scriptArgValue:e.file,profileArgValue:e.profile,sidecar:t}))}}let m,h,g,_;if(p)h=U.basename(n),m=Y.readFileSync(n,`utf-8`),c.info(`Using pre-bundled script ${l.bold(h)}`);else{c.info(`Detecting function type from ${l.path(f)}`);let t=await detectFunctionType({filePath:n,jobName:e.name});g=t.type,_=t.name,c.info(`Detected: ${l.bold(t.type)} ${l.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=U.dirname(r.path);({bundledCode:m,scriptName:h}=await bundleForRun({detected:t,sourceFile:n,baseDir:i,defaultPermission:t.type===`resolver`?Ln({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 ${l.bold(h)}`)}let v=br(i,{namespace:a,machineUserName:d.name});c.info(`Executing on workspace ${l.dim(u)}...`);let y;if(e.arg!==void 0)try{y=JSON.parse(e.arg)}catch(e){throw Error(`Invalid --arg JSON: ${e instanceof Error?e.message:e}`,{cause:e})}let b=await Re({client:s,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(l.bold(`
72
+ Logs:`));for(let e of b.logs.split(`
73
+ `))c.log(` ${e}`)}if(b.result&&b.success){c.log(l.bold(`
74
+ Result:`));try{let e=JSON.parse(b.result);c.log(` ${JSON.stringify(e,null,2).split(`
75
75
  `).join(`
76
- `)}`)}catch{c.log(` ${x.result}`)}}if(x.error&&!x.success){c.log(l.bold(`
77
- Error:`));let e=formatErrorWithSourcemap(x.error,h,process.cwd());e?c.log(e):c.log(` ${l.error(x.error)}`)}}x.success||process.exit(1)}}),li=new Set(dr(q.strictObject(Ie)).fields.filter(e=>e.type!==`boolean`).flatMap(e=>[e.cliName,...e.alias??[]].flatMap(toFlagTokens)));function toFlagTokens(e){return e.length===1?[`-${e}`]:[`--${e}`,`--${pr(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(`=`)&&li.has(r)&&n++}return t[0]===`function`&&t[1]===`test-run`}function resolveAuthNamespace(e){if(e?.name)return e.name;throw Error(`Auth namespace is required. Ensure tailor.config.ts has an auth config.`)}async function resolveMachineUserName(e){let{cliMachineUser:t,cliMachineUserSource:n,profile:r,authConfig:i}=e,a=await h({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 Error(`Machine user is required. 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 ui=N({name:`script`,description:"Scaffold a one-off script to run with `function run`.",args:q.object({...F,...ze,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=U.resolve(e.file);if(!t.endsWith(`.ts`))throw Error(`Script path must end with .ts: ${e.file}`);let n=U.dirname(t),r=Y.existsSync(t),i=U.join(n,ai),a=U.join(n,oi);if(t===i)throw Error(`${ai} is reserved for the generated Kysely types written next to the script. Choose a different script file name.`);let{config:s,plugins:u}=await M(e.config),d=u.find(e=>e.id===sr),f=Y.existsSync(a);if(e.remote&&d!==void 0&&r&&!f)throw Error(`Script already exists: ${U.relative(process.cwd(),t)}. 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:s,explicit:e.namespace,sidecarNamespace:m,remote:e.remote});if(m!==void 0&&m!==h)throw Error(`This directory's generated types target namespace "${m}" (${oi}). Scaffold scripts for namespace "${h}" in a separate directory.`);let g=[],_,v;if(p){let t;if(e.remote){let n=await C({profile:e.profile}),r=await B(n),i=await A({workspaceId:e[`workspace-id`],profile:e.profile});v=i,c.info(`Fetching deployed schema of namespace ${l.bold(h)}...`),t=await It(r,i,h)}else{c.info(`Loading local definitions of namespace ${l.bold(h)}...`);let{namespaces:n}=await je({configPath:e.config,namespaces:[h]}),r=o(n[0],`namespace ${h}`);t=ye(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 Error(`Namespace "${h}" has no ${t}.`)}if(Y.existsSync(i)&&!isGeneratedScriptDbTypes(Y.readFileSync(i,`utf-8`)))throw Error(`Refusing to overwrite ${U.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)+`
78
- `),g.push(a),_=`./db`}else{if(r)throw Error(`Script already exists: ${U.relative(process.cwd(),t)}. It imports the project's generated Kysely types, so there is nothing to refresh.`);let e=resolveKyselyTypesPath(u);_=toImportSpecifier(U.relative(n,e)),Y.existsSync(e)||c.warn(`Generated Kysely types not found at ${l.path(U.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`,U.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 ${l.path(U.relative(process.cwd(),e))}`);c.info(`Next: edit the script, then run ${Yn(y)}`)}});function resolveNamespace(e){let{config:t,explicit:n,sidecarNamespace:r,remote:i}=e,a=x(t),o=on(t),s=i?a:o;if(n){if(!i&&!o.includes(n))throw Error(`Namespace "${n}" is not owned by the config and requires --remote.`);return n}if(r!==void 0){if(!i&&!o.includes(r))throw Error(`Namespace "${r}" is not owned by the config and requires --remote.`);return r}if(s.length===1){let e=s[0];if(e!==void 0)return e}throw s.length>1?Error(`Multiple TailorDB namespaces are defined (${s.join(`, `)}). Specify one with --namespace.`):!i&&a.length>0?Error(`No owned TailorDB namespace is defined in the config. External namespaces require --remote: ${a.join(`, `)}.`):Error(`No TailorDB namespace is defined in the config.`)}function resolveKyselyTypesPath(e){let t=at(e,`@tailor-platform/kysely-type`)?.distPath??`./generated/tailordb.ts`;if(t.length===0)throw Error(`kyselyTypePlugin is configured without a distPath; cannot locate getDB().`);return U.resolve(t)}function toImportSpecifier(e){let t=e.replace(/\.ts$/,``);return t.startsWith(`.`)?t:`./${t}`}const di=G({name:`function`,description:`Manage functions`,subCommands:{get:Dt,list:w,logs:ii,run:ci,script:ui},async run(){await K(w,[])}}),fi=N({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 dn({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},pi=N({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 Gn(),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(` `)}`),Nr(r,i,{stdio:`inherit`})}}),mi=8085,hi=`http://localhost:${mi}/callback`;function randomState(){return Sr.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(`
76
+ `)}`)}catch{c.log(` ${b.result}`)}}if(b.error&&!b.success){c.log(l.bold(`
77
+ Error:`));let e=formatErrorWithSourcemap(b.error,m,process.cwd());e?c.log(e):c.log(` ${l.error(b.error)}`)}}b.success||process.exit(1)}}),mi=new Set(hr(q.strictObject(Gt)).fields.filter(e=>e.type!==`boolean`).flatMap(e=>[e.cliName,...e.alias??[]].flatMap(toFlagTokens)));function toFlagTokens(e){return e.length===1?[`-${e}`]:[`--${e}`,`--${_r(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(`=`)&&mi.has(r)&&n++}return t[0]===`function`&&t[1]===`test-run`}function resolveAuthNamespace(e){if(e?.name)return e.name;throw Error(`Auth namespace is required. Ensure tailor.config.ts has an auth config.`)}async function resolveMachineUserName(e){let{cliMachineUser:t,cliMachineUserSource:n,profile:r,authConfig:i}=e,a=await Me({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 Error(`Machine user is required. 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 hi=w({name:`script`,description:"Scaffold a one-off script to run with `function run`.",args:q.object({...N,...me,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=U.resolve(e.file);if(!t.endsWith(`.ts`))throw Error(`Script path must end with .ts: ${e.file}`);let n=U.dirname(t),r=Y.existsSync(t),i=U.join(n,ui),a=U.join(n,di);if(t===i)throw Error(`${ui} is reserved for the generated Kysely types written next to the script. Choose a different script file name.`);let{config:s,plugins:u}=await O(e.config),d=u.find(e=>e.id===dr),f=Y.existsSync(a);if(e.remote&&d!==void 0&&r&&!f)throw Error(`Script already exists: ${U.relative(process.cwd(),t)}. 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:s,explicit:e.namespace,sidecarNamespace:m,remote:e.remote});if(m!==void 0&&m!==h)throw Error(`This directory's generated types target namespace "${m}" (${di}). 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 D({profile:e.profile,workspaceId:e[`workspace-id`]});v=r,c.info(`Fetching deployed schema of namespace ${l.bold(h)}...`),t=await xt(n,r,h)}else{c.info(`Loading local definitions of namespace ${l.bold(h)}...`);let{namespaces:n}=await Ie({configPath:e.config,namespaces:[h]}),r=o(n[0],`namespace ${h}`);t=ie(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 Error(`Namespace "${h}" has no ${t}.`)}if(Y.existsSync(i)&&!isGeneratedScriptDbTypes(Y.readFileSync(i,`utf-8`)))throw Error(`Refusing to overwrite ${U.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)+`
78
+ `),g.push(a),_=`./db`}else{if(r)throw Error(`Script already exists: ${U.relative(process.cwd(),t)}. It imports the project's generated Kysely types, so there is nothing to refresh.`);let e=resolveKyselyTypesPath(u);_=toImportSpecifier(U.relative(n,e)),Y.existsSync(e)||c.warn(`Generated Kysely types not found at ${l.path(U.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`,U.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 ${l.path(U.relative(process.cwd(),e))}`);c.info(`Next: edit the script, then run ${$n(y)}`)}});function resolveNamespace(e){let{config:t,explicit:n,sidecarNamespace:r,remote:i}=e,a=x(t),o=ln(t),s=i?a:o;if(n){if(!i&&!o.includes(n))throw Error(`Namespace "${n}" is not owned by the config and requires --remote.`);return n}if(r!==void 0){if(!i&&!o.includes(r))throw Error(`Namespace "${r}" is not owned by the config and requires --remote.`);return r}if(s.length===1){let e=s[0];if(e!==void 0)return e}throw s.length>1?Error(`Multiple TailorDB namespaces are defined (${s.join(`, `)}). Specify one with --namespace.`):!i&&a.length>0?Error(`No owned TailorDB namespace is defined in the config. External namespaces require --remote: ${a.join(`, `)}.`):Error(`No TailorDB namespace is defined in the config.`)}function resolveKyselyTypesPath(e){let t=ot(e,`@tailor-platform/kysely-type`)?.distPath??`./generated/tailordb.ts`;if(t.length===0)throw Error(`kyselyTypePlugin is configured without a distPath; cannot locate getDB().`);return U.resolve(t)}function toImportSpecifier(e){let t=e.replace(/\.ts$/,``);return t.startsWith(`.`)?t:`./${t}`}const gi=G({name:`function`,description:`Manage functions`,subCommands:{get:kt,list:C,logs:li,run:pi,script:hi},async run(){await K(C,[])}}),_i=w({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 hn({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},vi=w({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 Yn(),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(` `)}`),Lr(r,i,{stdio:`inherit`})}}),yi=8085,bi=`http://localhost:${yi}/callback`;function randomState(){return Er.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(`
79
79
  `)}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 Error(H`
80
80
  Profile "${e.profile}" is configured for "${e.oldUser}", but login authenticated "${e.authenticatedUser}".
81
81
  The authenticated user has been saved. To use it with this profile, run:
82
82
  ${t}
83
83
  ${n}
84
- `)}function shouldUpdateCurrentUser(e,t){return!e||hn(t)}const startAuthServer=async(e={})=>{let t=An(e.platformConfig),n=randomState(),r=await xr(),i=await t.authorizationCode.getAuthorizeUri({redirectUri:hi,state:n,codeVerifier:r}).catch(e=>{throw Error(`Failed to prepare the login authorization URL: ${qn(e).message}`,{cause:e})});return new Promise((a,s)=>{let handleCallback=async(i,c)=>{try{if(!i.url?.startsWith(`/callback`))throw Error(`Invalid callback URL`);let s=await t.authorizationCode.getTokenFromCodeRedirect(`http://${i.headers.host}${i.url}`,{redirectUri:hi,state:n,codeVerifier:r}),l=await Cn(s.accessToken,e.platformConfig),u=await D();await pn(u,l.sub,{accessToken:s.accessToken,refreshToken:s.refreshToken??void 0},new Date(o(s.expiresAt,`token response missing expiresAt`)).toISOString(),{platformConfig:e.platformConfig,email:l.email});let d=getProfileUserMismatch(e,l.email,l.sub);if(d)throw _(u),profileUserMismatchError(d);(e.updateCurrentUser??!0)&&(u.current_user=l.sub),await se(u,l.email,l.sub,e.platformConfig),_(u),c.writeHead(200,{"Content-Type":`application/json`}),c.end(JSON.stringify({status:`ok`,message:`Successfully authenticated. Please close this window.`})),a()}catch(e){c.writeHead(401),c.end(`Authentication failed`),s(qn(e))}finally{l.close()}},l=wr.createServer((e,t)=>void handleCallback(e,t)),u=setTimeout(()=>{l.close(),s(Error(`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 Tr(i)}catch{c.warn(`Failed to open browser automatically. Please open the URL above manually.`)}};l.listen(mi,()=>void openBrowser())})};async function loginAsMachineUser(e){let t=e.clientSecret??await z.password({message:`Client secret`}),n=await bn(e.clientId,t,e.platformConfig),r=await D();await pn(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 _(r),profileUserMismatchError(i);(e.updateCurrentUser??!0)&&(r.current_user=e.clientId),_(r)}const gi=N({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 D()).profiles[e.profile];if(!r)throw Error(`Profile "${e.profile}" not found`);t=j(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 Vn()}}}),_i=N({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 D(),r=t?n.profiles[t]:void 0;if(t&&!r)throw Error(`Profile "${t}" not found`);let i=r?j(r):void 0,a=r?r.user:n.current_user,o=hn(i),s=t?{allowLegacyUserKey:!0}:void 0;if(!a){c.info(`You are not logged in.`);return}let hasDefaultUserToken=()=>te(n,a,{platformUrl:_n}),shouldClearCurrentUser=()=>n.current_user===a&&(o||!Ne(n,a))&&!hasDefaultUserToken(),l,u=!1;try{l=await ge(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),_(n);return}if(l)try{let e=An(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 b(n,a,i,s),shouldClearCurrentUser()&&(n.current_user=null),_(n),c.success(`Successfully logged out from Tailor Platform.`)}}),vi=G({name:`machineuser`,description:`Manage machine users in your Tailor Platform application.`,subCommands:{list:Qe,token:_t},async run(){await K(Qe,[])}}),yi=G({name:`oauth2client`,description:`Manage OAuth2 clients in your Tailor Platform application.`,subCommands:{list:ct,get:Rt},async run(){await K(ct,[])}}),bi=N({name:`open`,description:`Open Tailor Platform Console.`,args:q.strictObject({...L}),run:async e=>{let t=await A({workspaceId:e[`workspace-id`],profile:e.profile}),{config:n}=await M(e.config),r=n.name,i=s(process.env.TAILOR_CONSOLE_NEXT)===!0?`/workspaces/${t}/services/applications/${encodeURIComponent(r)}`:`/workspaces/${t}/applications/${encodeURIComponent(r)}/overview`,a=await Et({profile:e.profile,...e[`workspace-id`]===void 0?{}:{allowMissingProfile:!0}}),o=new URL(i,a).toString(),l=c.jsonMode;c.info(`Opening Tailor Platform Console...`);let u=!0;try{await Tr(o)}catch{u=!1}if(l){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}`)}}),xi=G({name:`folder`,description:`Manage organization folders.`,subCommands:{create:kt,delete:Gt,get:nt,list:Ht,update:Yt}}),Si=G({name:`organization`,description:`Manage Tailor Platform organizations.`,subCommands:{folder:xi,get:u,list:qe,tree:Ve,update:zt},async run(){await K(qe,[])}}),Ci=`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(`.`),wi={seed:`@tailor-platform/sdk-plugin-seed`,setup:`@tailor-platform/sdk-plugin-setup`,"tailordb-erd":`@tailor-platform/sdk-plugin-tailordb-erd`},Ti=process.platform===`win32`?`;`:`:`;function*ancestorDirs(e){let t=U.resolve(e),n=U.dirname(t);for(;n!==t;)yield t,t=n,n=U.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{_r(e,process.platform===`win32`?vr.F_OK:vr.X_OK)}catch{return!1}if(process.platform===`win32`){let t=U.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(Ti).filter(Boolean)}function nodeModulesBinDirs(){let e=[];for(let t of ancestorDirs(process.cwd()))e.push(U.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=U.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=U.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=yr(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=U.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 D(),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 Gn();e&&(n.TAILOR_VERSION=e)}catch{}let i=Ce();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=On(a),n.TAILOR_PLATFORM_OAUTH2_CLIENT_ID=Sn(a);try{n.TAILOR_PLATFORM_WORKSPACE_ID=await A({profile:t})}catch{}try{let e=await resolveActiveUser(t);e&&(n.TAILOR_PLATFORM_USER=e)}catch{}try{let e=await C({profile:t});e&&(n.TAILOR_PLATFORM_TOKEN=e)}catch{}return n}function signalToExitCode(e){let t=Or.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=U.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=Mr(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=wi[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 Ei=N({name:`list`,description:"List discovered plugins (executables named `<cli>-<name>` on PATH or node_modules/.bin).",args:q.strictObject({}),run:async()=>{let e=await Gn(),t=Object.keys(e.bin??{})[0]||`tailor`,n=new Set(Ci),r=listPlugins(t);if(r.length===0){c.info(H`
84
+ `)}function shouldUpdateCurrentUser(e,t){return!e||vn(t)}const startAuthServer=async(e={})=>{let t=Pn(e.platformConfig),n=randomState(),r=await Tr(),i=await t.authorizationCode.getAuthorizeUri({redirectUri:bi,state:n,codeVerifier:r}).catch(e=>{throw Error(`Failed to prepare the login authorization URL: ${Zn(e).message}`,{cause:e})});return new Promise((a,s)=>{let handleCallback=async(i,c)=>{try{if(!i.url?.startsWith(`/callback`))throw Error(`Invalid callback URL`);let s=await t.authorizationCode.getTokenFromCodeRedirect(`http://${i.headers.host}${i.url}`,{redirectUri:bi,state:n,codeVerifier:r}),l=await En(s.accessToken,e.platformConfig),u=await B();await ze(u,l.sub,{accessToken:s.accessToken,refreshToken:s.refreshToken??void 0},new Date(o(s.expiresAt,`token response missing expiresAt`)).toISOString(),{platformConfig:e.platformConfig,email:l.email});let d=getProfileUserMismatch(e,l.email,l.sub);if(d)throw k(u),profileUserMismatchError(d);(e.updateCurrentUser??!0)&&(u.current_user=l.sub),await _(u,l.email,l.sub,e.platformConfig),k(u),c.writeHead(200,{"Content-Type":`application/json`}),c.end(JSON.stringify({status:`ok`,message:`Successfully authenticated. Please close this window.`})),a()}catch(e){c.writeHead(401),c.end(`Authentication failed`),s(Zn(e))}finally{l.close()}},l=Or.createServer((e,t)=>void handleCallback(e,t)),u=setTimeout(()=>{l.close(),s(Error(`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 kr(i)}catch{c.warn(`Failed to open browser automatically. Please open the URL above manually.`)}};l.listen(yi,()=>void openBrowser())})};async function loginAsMachineUser(e){let t=e.clientSecret??await z.password({message:`Client secret`}),n=await Cn(e.clientId,t,e.platformConfig),r=await B();await ze(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 k(r),profileUserMismatchError(i);(e.updateCurrentUser??!0)&&(r.current_user=e.clientId),k(r)}const xi=w({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 B()).profiles[e.profile];if(!r)throw Error(`Profile "${e.profile}" not found`);t=Pe(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 Gn()}}}),Si=w({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 B(),r=t?n.profiles[t]:void 0;if(t&&!r)throw Error(`Profile "${t}" not found`);let i=r?Pe(r):void 0,a=r?r.user:n.current_user,o=vn(i),s=t?{allowLegacyUserKey:!0}:void 0;if(!a){c.info(`You are not logged in.`);return}let hasDefaultUserToken=()=>Ot(n,a,{platformUrl:bn}),shouldClearCurrentUser=()=>n.current_user===a&&(o||!ke(n,a))&&!hasDefaultUserToken(),l,u=!1;try{l=await fe(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),k(n);return}if(l)try{let e=Pn(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 re(n,a,i,s),shouldClearCurrentUser()&&(n.current_user=null),k(n),c.success(`Successfully logged out from Tailor Platform.`)}}),Ci=G({name:`machineuser`,description:`Manage machine users in your Tailor Platform application.`,subCommands:{list:$e,token:bt},async run(){await K($e,[])}}),wi=G({name:`oauth2client`,description:`Manage OAuth2 clients in your Tailor Platform application.`,subCommands:{list:dt,get:Ht},async run(){await K(dt,[])}}),Ti=w({name:`open`,description:`Open Tailor Platform Console.`,args:q.strictObject({...j}),run:async e=>{let t=await ve({workspaceId:e[`workspace-id`],profile:e.profile}),{config:n}=await O(e.config),r=n.name,i=s(process.env.TAILOR_CONSOLE_NEXT)===!0?`/workspaces/${t}/services/applications/${encodeURIComponent(r)}`:`/workspaces/${t}/applications/${encodeURIComponent(r)}/overview`,a=await Te({profile:e.profile,...e[`workspace-id`]===void 0?{}:{allowMissingProfile:!0}}),o=new URL(i,a).toString(),l=c.jsonMode;c.info(`Opening Tailor Platform Console...`);let u=!0;try{await kr(o)}catch{u=!1}if(l){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}`)}}),Ei=G({name:`folder`,description:`Manage organization folders.`,subCommands:{create:Mt,delete:Zt,get:rt,list:Jt,update:tn}}),Di=G({name:`organization`,description:`Manage Tailor Platform organizations.`,subCommands:{folder:Ei,get:u,list:Ye,tree:Ge,update:Ut},async run(){await K(Ye,[])}}),Oi=`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(`.`),ki={seed:`@tailor-platform/sdk-plugin-seed`,setup:`@tailor-platform/sdk-plugin-setup`,"tailordb-erd":`@tailor-platform/sdk-plugin-tailordb-erd`},Ai=process.platform===`win32`?`;`:`:`;function*ancestorDirs(e){let t=U.resolve(e),n=U.dirname(t);for(;n!==t;)yield t,t=n,n=U.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{xr(e,process.platform===`win32`?Sr.F_OK:Sr.X_OK)}catch{return!1}if(process.platform===`win32`){let t=U.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(Ai).filter(Boolean)}function nodeModulesBinDirs(){let e=[];for(let t of ancestorDirs(process.cwd()))e.push(U.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=U.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=U.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=Cr(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=U.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 B(),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 Yn();e&&(n.TAILOR_VERSION=e)}catch{}let i=xe();if(i&&(n.TAILOR_CONFIG_PATH=i),e.skipPlatformContext)return n;let a;try{a=await ae({profile:t,allowMissingProfile:!0})}catch{}n.TAILOR_PLATFORM_URL=Mn(a),n.TAILOR_PLATFORM_OAUTH2_CLIENT_ID=Tn(a);try{n.TAILOR_PLATFORM_WORKSPACE_ID=await ve({profile:t})}catch{}try{let e=await resolveActiveUser(t);e&&(n.TAILOR_PLATFORM_USER=e)}catch{}try{let e=await h({profile:t});e&&(n.TAILOR_PLATFORM_TOKEN=e)}catch{}return n}function signalToExitCode(e){let t=Mr.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=U.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=Ir(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=ki[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 ji=w({name:`list`,description:"List discovered plugins (executables named `<cli>-<name>` on PATH or node_modules/.bin).",args:q.strictObject({}),run:async()=>{let e=await Yn(),t=Object.keys(e.bin??{})[0]||`tailor`,n=new Set(Oi),r=listPlugins(t);if(r.length===0){c.info(H`
85
85
  No plugins found.
86
86
  Install an executable named "${t}-<name>" on your PATH or in node_modules/.bin,
87
87
  then run it with "${t} <name>".
88
- `),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.`)}}),Di=G({name:`plugin`,description:`Manage and inspect CLI plugins (beta).`,subCommands:{list:Ei},async run(){await K(Ei,[])}}),Oi=N({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 Error(`--machine-user-override deny requires --machine-user.`);let t=await D();if(t.profiles[e.name])throw Error(`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 an(t,e.user,r),o=await B(i,r);if(!(await Dn(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 Error(`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`]}:{}},_(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)}}),ki=N({name:`delete`,description:`Delete a profile.`,args:q.strictObject({name:W(q.string(),{positional:!0,description:`Profile name`})}),run:async e=>{let t=await D();if(!t.profiles[e.name])throw Error(`Profile "${e.name}" not found.`);delete t.profiles[e.name],_(t),c.success(`Profile "${e.name}" deleted successfully.`)}}),Ai=N({name:`list`,description:`List all profiles.`,args:q.strictObject({}),run:async()=>{let e=await D(),t=c.jsonMode,n=Object.entries(e.profiles);if(n.length===0){c.info(H`
88
+ `),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.`)}}),Mi=G({name:`plugin`,description:`Manage and inspect CLI plugins (beta).`,subCommands:{list:ji},async run(){await K(ji,[])}}),Ni=w({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 Error(`--machine-user-override deny requires --machine-user.`);let t=await B();if(t.profiles[e.name])throw Error(`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 S(t,e.user,r),o=await kn(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 Error(`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`]}:{}},k(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)}}),Pi=w({name:`delete`,description:`Delete a profile.`,args:q.strictObject({name:W(q.string(),{positional:!0,description:`Profile name`})}),run:async e=>{let t=await B();if(!t.profiles[e.name])throw Error(`Profile "${e.name}" not found.`);delete t.profiles[e.name],k(t),c.success(`Profile "${e.name}" deleted successfully.`)}}),Fi=w({name:`list`,description:`List all profiles.`,args:q.strictObject({}),run:async()=>{let e=await B(),t=c.jsonMode,n=Object.entries(e.profiles);if(n.length===0){c.info(H`
89
89
  No profiles found.
90
90
  Please create a profile first using 'tailor profile create' command.
91
- `),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)}}),ji=N({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 D(),n=t.profiles[e.name];if(!n)throw Error(`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 Error(`Please provide at least one property to 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`]===``?j(n):h;if((e[`machine-user`]!==void 0||e[`machine-user-override`]!==void 0)&&u===`deny`&&!l)throw e[`machine-user-override`]===`deny`?Error(`--machine-user-override deny requires --machine-user.`):Error(`Cannot clear the machine user while machine-user-override is "deny". Also pass --machine-user-override allow.`);if(e.user!==void 0||e[`workspace-id`]!==void 0||e[`platform-url`]!==void 0){let e=await an(t,i,g);s=e.user;let n=await B(e.accessToken,h);if(!(await Dn(async(e,t)=>{let{workspaces:r,nextPageToken:i}=await n.listWorkspaces({pageToken:e,pageSize:t});return[r,i]})).find(e=>e.id===o))throw Error(`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`]),_(t),e.json||c.success(`Profile "${e.name}" updated successfully`);let v={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(v)}}),Mi=G({name:`profile`,description:`Manage workspace profiles (user + workspace combinations).`,subCommands:{create:Oi,delete:ki,list:Ai,update:ji},async run(){await K(Ai,[])}}),Ni={"vault-name":W(q.string(),{alias:`V`,description:`Vault name`})},Pi={...Ni,name:W(q.string(),{alias:`n`,description:`Secret name`})},Fi={...Pi,value:W(q.string(),{alias:`v`,description:`Secret value`})};async function checkVaultManaged(e){let{client:t,workspaceId:n,vaultName:r}=e,i=I(n,`vault`,r),a={isManaged:!1,trn:i,existingLabels:{}},o,s;try{let{metadata:e}=await t.getMetadata({trn:i});s=e?.labels??{},o=s[gt]}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 tn(t,{trn:n,remove:[gt,Ze,yt]}),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 Ii=N({name:`create`,description:`Create a secret in a vault.`,args:q.strictObject({...F,...Fi,...O}),run:async e=>{await R({profile:e.profile});let t=await C({profile:e.profile}),n=await B(t),r=await A({workspaceId:e[`workspace-id`],profile:e.profile}),i=await checkVaultManaged({client:n,workspaceId:r,vaultName:e[`vault-name`]});if(!(i.isManaged&&!e.yes&&!await z.confirm({message:`Do you want to proceed?`,default:!1}))){try{await n.createSecretManagerSecret({workspaceId:r,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name,secretmanagerSecretValue:e.value})}catch(t){if(t instanceof Q){if(t.code===Z.NotFound)throw Error(`Vault "${e[`vault-name`]}" not found.`,{cause:t});if(t.code===Z.AlreadyExists)throw Error(`Secret "${e.name}" already exists.`,{cause:t})}throw t}i.isManaged&&await releaseVaultOwnership({client:n,...i}),c.success(`Secret: ${e.name} created in vault: ${e[`vault-name`]}`)}}}),Li=N({name:`delete`,description:`Delete a secret in a vault.`,args:q.strictObject({...F,...Pi,...O}),run:async e=>{await R({profile:e.profile});let t=await C({profile:e.profile}),n=await B(t),r=await A({workspaceId:e[`workspace-id`],profile:e.profile}),i=await checkVaultManaged({client:n,workspaceId:r,vaultName:e[`vault-name`]});if(!e.yes&&await z.text({message:`Enter the secret name to confirm deletion ("${e.name}"):`})!==e.name){c.info(`Secret deletion cancelled.`);return}try{await n.deleteSecretManagerSecret({workspaceId:r,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?Error(`Secret "${e.name}" not found in vault "${e[`vault-name`]}".`,{cause:t}):t}i.isManaged&&await releaseVaultOwnership({client:n,...i}),c.success(`Secret: ${e.name} 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 t=await C({profile:e.profile}),n=await B(t),r=await A({workspaceId:e.workspaceId,profile:e.profile}),i=f(e.order);return(await V(async(t,a)=>{let{secrets:o,nextPageToken:s}=await n.listSecretManagerSecrets({workspaceId:r,secretmanagerVaultName:e.vaultName,pageToken:t,pageSize:a,pageDirection:i});return[o,s]},{limit:e.limit})).map(secretInfo)}const Ri=N({name:`list`,description:`List all secrets in a vault.`,args:q.strictObject({...F,...Ni,...Ye()}),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?Error(`Vault "${e[`vault-name`]}" not found.`,{cause:t}):t}}}),zi=N({name:`update`,description:`Update a secret in a vault.`,args:q.strictObject({...F,...Fi,...O}),run:async e=>{await R({profile:e.profile});let t=await C({profile:e.profile}),n=await B(t),r=await A({workspaceId:e[`workspace-id`],profile:e.profile}),i=await checkVaultManaged({client:n,workspaceId:r,vaultName:e[`vault-name`]});if(!(i.isManaged&&!e.yes&&!await z.confirm({message:`Do you want to proceed?`,default:!1}))){try{await n.updateSecretManagerSecret({workspaceId:r,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name,secretmanagerSecretValue:e.value})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?Error(`Secret "${e.name}" not found in vault "${e[`vault-name`]}".`,{cause:t}):t}i.isManaged&&await releaseVaultOwnership({client:n,...i}),c.success(`Secret: ${e.name} updated in vault: ${e[`vault-name`]}`)}}}),Bi={name:W(q.string(),{positional:!0,description:`Vault name`})},Vi=N({name:`create`,description:`Create a new Secret Manager vault.`,args:q.strictObject({...F,...Bi}),run:async e=>{await R({profile:e.profile});let t=await C({profile:e.profile}),n=await B(t),r=await A({workspaceId:e[`workspace-id`],profile:e.profile});try{await n.createSecretManagerVault({workspaceId:r,secretmanagerVaultName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.AlreadyExists?Error(`Vault "${e.name}" already exists.`,{cause:t}):t}c.success(`Vault: ${e.name} created`)}}),Hi=N({name:`delete`,description:`Delete a Secret Manager vault.`,args:q.strictObject({...F,...Bi,...O}),run:async e=>{await R({profile:e.profile});let t=await C({profile:e.profile}),n=await B(t),r=await A({workspaceId:e[`workspace-id`],profile:e.profile}),i=await checkVaultManaged({client:n,workspaceId:r,vaultName:e.name});if(!e.yes&&await z.text({message:`Enter the vault name to confirm deletion ("${e.name}"):`})!==e.name){c.info(`Vault deletion cancelled.`);return}try{await n.deleteSecretManagerVault({workspaceId:r,secretmanagerVaultName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?Error(`Vault "${e.name}" not found.`,{cause:t}):t}i.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 t=await C({profile:e?.profile}),n=await B(t),r=await A({workspaceId:e?.workspaceId,profile:e?.profile}),i=f(e?.order);return(await V(async(e,t)=>{let{vaults:a,nextPageToken:o}=await n.listSecretManagerVaults({workspaceId:r,pageToken:e,pageSize:t,pageDirection:i});return[a,o]},{limit:e?.limit})).map(vaultInfo)}const Ui=N({name:`list`,description:`List all Secret Manager vaults in the workspace.`,args:q.strictObject({...F,...Ye()}),run:async e=>{let t=await vaultList({workspaceId:e[`workspace-id`],profile:e.profile,order:e.order,limit:e.limit});c.out(t)}}),Wi=G({name:`vault`,description:`Manage Secret Manager vaults.`,subCommands:{create:Vi,delete:Hi,list:Ui},async run(){await K(Ui,[])}}),Gi=G({name:`secret`,description:`Manage Secret Manager vaults and secrets.`,subCommands:{vault:Wi,create:Ii,update:zi,list:Ri,delete:Li},async run(){await K(Wi,[])}}),Ki={[t.UNSPECIFIED]:`unspecified`,[t.PENDING]:`pending`,[t.VERIFYING]:`verifying`,[t.CERT_ISSUED]:`cert_issued`,[t.ACTIVE]:`active`,[t.FAILED]:`failed`},qi=N({name:`get`,description:`Get details of a custom domain.`,args:q.strictObject({...F,domain:W(q.string(),{positional:!0,description:`Custom domain name`})}),run:async e=>{let t=await C({profile:e.profile}),n=await B(t),r=await A({workspaceId:e[`workspace-id`],profile:e.profile}),i=`Custom domain "${e.domain}" not found.`;try{let{customDomain:t}=await n.getCustomDomain({workspaceId:r,domain:e.domain});if(!t)throw Error(i);let a={domain:t.domain,status:Ki[t.status]??`unknown`,trafficCnameTarget:t.trafficCnameTarget,certificateCnameTarget:t.certificateCnameTarget,errorMessage:t.errorMessage||void 0};c.out(a)}catch(e){throw e instanceof Q&&e.code===Z.NotFound?Error(i,{cause:e}):e}}}),Ji=N({name:`list`,description:`List custom domains for a static website.`,args:q.strictObject({...F,name:W(q.string(),{positional:!0,description:`Static website name`})}),run:async e=>{let t=await C({profile:e.profile}),n=await B(t),r=await A({workspaceId:e[`workspace-id`],profile:e.profile});try{let{customDomains:t}=await n.listCustomDomains({workspaceId:r,staticWebsiteName:e.name});if(t.length===0){c.info(`No custom domains found.`),c.jsonMode&&c.out([]);return}let i=t.map(e=>({domain:e.domain,status:Ki[e.status]??`unknown`,trafficCnameTarget:e.trafficCnameTarget,certificateCnameTarget:e.certificateCnameTarget}));c.out(i)}catch(t){throw t instanceof Q&&t.code===Z.NotFound?Error(`Static website "${e.name}" not found.`,{cause:t}):t}}}),Yi=G({name:`domain`,description:`Manage custom domains for static websites.`,subCommands:{list:Ji,get:qi}}),Xi=N({name:`get`,description:`Get details of a specific static website.`,args:q.strictObject({...F,name:W(q.string(),{positional:!0,description:`Static website name`})}),run:async e=>{let t=await C({profile:e.profile}),n=await B(t),r=await A({workspaceId:e[`workspace-id`],profile:e.profile}),i=`Static website "${e.name}" not found.`;try{let{staticwebsite:t}=await n.getStaticWebsite({workspaceId:r,name:e.name});if(!t)throw Error(i);let a={workspaceId:r,name:t.name,description:t.description,url:t.url,allowedIpAddresses:e.json?t.allowedIpAddresses:t.allowedIpAddresses.join(`
92
- `)};c.out(a)}catch(e){throw e instanceof Q&&e.code===Z.NotFound?Error(i,{cause:e}):e}}});async function listStaticWebsites(e){let t=await C({profile:e?.profile}),n=await B(t),r=await A({workspaceId:e?.workspaceId,profile:e?.profile}),i=f(e?.order);return(await V(async(e,t)=>{let{staticwebsites:a,nextPageToken:o}=await n.listStaticWebsites({workspaceId:r,pageToken:e,pageSize:t,pageDirection:i});return[a,o]},{limit:e?.limit})).map(e=>({workspaceId:r,name:e.name,description:e.description,url:e.url,allowedIpAddresses:e.allowedIpAddresses}))}const Zi=N({name:`list`,description:`List all static websites in a workspace.`,args:q.strictObject({...F,...Ye()}),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)}}),Qi=G({name:`staticwebsite`,description:`Manage static websites in your workspace.`,subCommands:{deploy:Le,domain:Yi,list:Zi,get:Xi},async run(){await K(Zi,[])}}),$i=new Set(Object.values(ie));async function activateBaseline(e,t,n,r){let i=await $.realpath(e),a=U.dirname(i),o=U.basename(i),s=await $.mkdtemp(U.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()||!Fe.test(e.name))continue;let t=U.join(s,e.name);(await $.readdir(t)).some(e=>$i.has(e))&&await $.rm(t,{recursive:!0,force:!0})}let e={...t,namespace:n,version:5,createdAt:new Date().toISOString(),rebaseline:r},a=await fn(e,s,0);Ee(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){g(`tailordb migration`);let{config:t,plugins:n}=await M(e.configPath),r=U.dirname(t.path),i=Se(S(t,r),e.namespace),a=Zn({command:`tailor`,args:[`tailordb`,`migration`,`generate`,`--config`,t.path]});E(i.migrationsDir,i.namespace);let o=k(i.migrationsDir);if(!o)throw Error(`No migration history found for namespace "${i.namespace}". Run ${a} first.`);let s=ue(i.migrationsDir),u=k(i.migrationsDir,0)?.rebaseline?.historyId??null,d=m([i])[i.namespace],f=n.length>0?new Zt(n):void 0,{defineApplication:p}=await import(`../application-B4tCGHiQ.mjs`),h=p({config:t,pluginManager:f});for(let e of h.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let _=h.tailorDBServices.find(e=>e.namespace===i.namespace);if(!_)throw Error(`No TailorDB service found for namespace "${i.namespace}"`);let assertLocalTypesReady=()=>{let e=ye(_.types,i.namespace),t=xt(o,e.tables,i.namespace);if(pt(t))throw c.error(`Migration history does not reproduce the current local schema for namespace ${l.bold(i.namespace)}:`),c.log(st(t)),Error(`Refusing to re-baseline: the migration history must reproduce the current local schema. Run ${a} first.`)},localSourceFiles=()=>[t.path,...Hn(_.config,r)];assertLocalTypesReady();let v=Tt(localSourceFiles()),y=await C({profile:e.profile}),b=await B(y),x=await A({workspaceId:e.workspaceId,profile:e.profile}),w=[`--config`,t.path,`--workspace-id`,x,...e.profile?[`--profile`,e.profile]:[]],ee=Zn({command:`tailor`,args:[`tailordb`,`migration`,`set`,`0`,`--namespace`,i.namespace,...w]}),te=Zn({command:`tailor`,args:[`deploy`,...w]}),assertConnectedWorkspaceReady=async(e,n)=>{let r=await T(b,I(x,`tailordb`,i.namespace)),a=r.number;if(a!==s){let e=a===null?`<unset>`:P(a);throw Error(`The connected workspace must be at the latest migration ${P(s)} before re-baselining; current checkpoint is ${e}.`)}if(r.historyIdInvalid)throw Error(`Refusing to re-baseline: the connected workspace has an invalid migration history marker.`);if(r.historyId!==e)throw Error(n===`confirmation`?`The connected workspace migration history changed while waiting for confirmation. Run the command again.`:`Refusing to re-baseline: the connected workspace does not match the local migration history.`);let o=await Xe(b,x,[i],t,[ht(_)]),l=o[0];if(!l||l.remoteMigrationNumber!==s||l.hasDrift||l.checkpointMissingLocal)throw l?.hasDrift&&(c.error(`Remote schema drift detected:`),c.log(jt(o))),Error(`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 ${l.bold(i.namespace)}.`),c.log(` Latest migration: ${P(s)}`),c.log(` New history: 0000/schema.json only`),c.log(` migrate.ts and db.ts files will disappear from the working tree.`),c.log(` Committed migration files will remain in Git history. Preserve any uncommitted files before continuing.`),c.log(` Every other environment must already be at the latest migration.`),c.log(` The connected workspace checkpoint will be reset to 0000.`),c.newline(),!e.yes&&!await z.confirm({message:`Re-baseline this migration history and reset the connected workspace checkpoint?`,default:!1})){c.info(`Operation cancelled.`);return}if(E(i.migrationsDir,i.namespace),m([i])[i.namespace]!==d)throw Error(`Migration files changed while waiting for confirmation. Run the command again.`);if(Tt(localSourceFiles())!==v)throw Error(`Local TailorDB table or config files changed. Run the command again.`);assertLocalTypesReady(),await assertConnectedWorkspaceReady(u,`confirmation`);let D={historyId:Jt(),replacedHistoryId:u,replacedLatestMigration:s};await activateBaseline(i.migrationsDir,o,i.namespace,D);try{await un(b,x,i.namespace,0,D.historyId)}catch(e){throw Error(`The local migration history was re-baselined, but the connected workspace checkpoint could not be updated. Run ${ee}, or run ${te} with schema checks enabled after resolving the connection error.`,{cause:e})}c.success(`Re-baselined ${l.bold(i.namespace)} and reset the connected workspace checkpoint to 0000.`)}const ea=N({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({...L,...O,namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await R({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){g(`tailordb migration`);let t=Ot(e.number),{config:n}=await M(e.configPath),r=U.dirname(n.path),i=S(n,r),a=Se(i,e.namespace),o=a.namespace;E(a.migrationsDir,o),re(a.migrationsDir,t);let s=k(a.migrationsDir,0)?.rebaseline?.historyId,u=await C({profile:e.profile}),f=await B(u),p=await A({workspaceId:e.workspaceId,profile:e.profile}),m=I(p,`tailordb`,o),h=await T(f,m),_=h.number,v=_??0,y=h.historyIdInvalid?`<invalid>`:h.historyId??`<unset>`,b=s??`<unset>`;if(c.newline(),c.warn(`This operation will change TailorDB migration state metadata.`),c.log(`Namespace: ${l.bold(o)}`),c.log(`Current migration: ${_===null?`<unset>`:l.bold(P(_))}`),c.log(`New migration: ${l.bold(P(t))}`),c.log(`Current migration history ID: ${l.bold(y)}`),c.log(`New migration history ID: ${l.bold(b)}`),c.newline(),t<v?(c.warn(`Setting migration number backwards (${P(v)} → ${P(t)}) will cause previous migrations to be re-executed on next apply.`),c.newline()):t>v&&(c.warn(`Setting migration number forwards (${P(v)} → ${P(t)}) will skip migrations ${P(v+1)} to ${P(t)}.`),c.newline()),!e.yes){if(!await z.confirm({message:`Continue with migration checkpoint and history ID update?`,default:!1})){c.info(`Operation cancelled.`);return}c.newline()}await tn(f,{trn:m,labels:{[ut]:Vt(t),...s?{[d]:s}:{}},remove:s?void 0:[d]}),c.success(`Migration checkpoint set to ${l.bold(P(t))} for namespace ${l.bold(o)}`)}const ta=N({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({...L,...O,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 R({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 M(e.configPath),n=U.dirname(t.path),r=S(t,n);if(r.length===0)throw Error(`No TailorDB services with migrations configuration found`);let i=e.namespace?r.filter(t=>t.namespace===e.namespace):r;if(i.length===0)throw Error(`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=We(t),r=new Map,i=null;for(let e of n){if(e.type===`schema`){let t=Ee(e.path);e.number===0&&(i=t.rebaseline?.historyId??null);continue}try{let t=Je(e.path);t.description&&r.set(e.number,t.description)}catch(e){if(e instanceof Ft)throw e}}a.set(e,{migrationFiles:n,descriptions:r,historyId:i})}catch(t){o.set(e,t instanceof Error?t.message:String(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 s=await C({profile:e.profile}),c=await B(s),l=await A({workspaceId:e.workspaceId,profile:e.profile}),u=[];for(let{namespace:e}of i){if(o.has(e)){u.push({status:`error`,namespace:e,error:o.get(e)??`Failed to read local migration history.`});continue}let t=a.get(e);if(!t){u.push({status:`error`,namespace:e,error:`Failed to read local migration history.`});continue}let{migrationFiles:n,descriptions:r,historyId:i}=t,s=I(l,`tailordb`,e),d;try{d=await T(c,s)}catch(t){u.push({status:`error`,namespace:e,error:t instanceof Error?t.message:String(t)});continue}let f=d.number??0;if(d.historyIdInvalid){u.push({status:`error`,namespace:e,error:`Remote migration history ID is invalid.`});continue}if((d.number!==null||d.historyId!==null)&&d.historyId!==i){u.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:P(e),...r.has(e)?{description:r.get(e)}:{}}));u.push({status:`ok`,namespace:e,currentMigration:f,currentMigrationLabel:P(f),pendingMigrations:p})}return u}function printMigrationStatuses(e){for(let t of e){if(c.newline(),c.info(`Namespace: ${l.bold(t.namespace)}`),isStatusFailure(t)){c.error(` Migration status error: ${t.error}`);continue}if(c.log(` Current migration: ${l.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){g(`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 Error(`Migration status check failed for ${n.length} namespace${n.length===1?``:`s`}: ${e}`)}}const na=N({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({...L,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 xn(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 Dn(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?Error(`Cannot sync: TailorDB namespace "${n}" has not been deployed yet.`,{cause:e}):e}})}async function assertMigrationsReproduceLocalTypes(e,t){let{config:n,plugins:r}=e,i=r.length>0?new Zt(r):void 0,{defineApplication:a,generatePluginFilesIfNeeded:o}=await import(`../application-B4tCGHiQ.mjs`),s=a({config:n,pluginManager:i}),u=s.tailorDBServices.find(e=>e.namespace===t.namespace);if(!u)throw Error(`No TailorDB service found for namespace "${t.namespace}"`);for(let e of s.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let d=o(i,s.tailorDBServices,n.path),f=s.executorService??(d.length>0?(await import(`../service-CmwD9bwv.mjs`)).createExecutorService({config:{files:[]},baseDir:U.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??{}))Lt(e)&&e.trigger.kind===`tailordb`&&p.add(e.trigger.tableName);let m={executorUsedTables:p,namespaceGqlOperations:u.config.gqlOperations},h=k(t.migrationsDir);if(!h)return m;let g=ye(u.types,t.namespace),_=xt(h,g.tables,t.namespace);if(!pt(_))return m;throw c.error(`Migration history does not reproduce the current local schema for namespace ${l.bold(t.namespace)}:`),c.log(st(_)),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(),Error(`Refusing to sync: the migration history must reproduce the current local schema before it can be applied to the remote.`)}async function sync(e){g(`tailordb migration`);let t=Ot(e.number),n=await M(e.configPath),{config:r}=n,i=U.dirname(r.path),a=S(r,i),o=Se(a,e.namespace);E(o.migrationsDir,o.namespace);let s=re(o.migrationsDir,t),u=k(o.migrationsDir,t);if(!u)throw Error(`No initial schema snapshot found in ${o.migrationsDir}. Expected 0000/schema.json.`);let f=await assertMigrationsReproduceLocalTypes(n,o),p=await C({profile:e.profile}),m=await B(p),h=await A({workspaceId:e.workspaceId,profile:e.profile}),_=I(h,`tailordb`,o.namespace),v=await Me(m,_),b=await fetchRemoteTypes(m,h,o.namespace),x=new Set(b.map(e=>e.name)),{creates:w,updates:ee,deletes:T}=Ae(u,x),te=await fetchRemoteGqlPermissions(m,h,o.namespace),D=new Set(te.map(e=>e.typeName)),ne=Object.entries(u.tables).flatMap(([e,t])=>t.permissions?.gql?[{typeName:e,permission:rn(t.permissions.gql)}]:[]),O=new Set(ne.map(e=>e.typeName)),ie=te.filter(e=>!O.has(e.typeName));if(c.newline(),c.info(`Namespace: ${l.bold(o.namespace)}`),c.log(` Current migration: ${v===null?`<unset>`:l.bold(P(v))}`),c.log(` Target migration: ${l.bold(P(t))}`),c.log(` Tables to create: ${l.bold(String(w.length))}`),c.log(` Tables to update: ${l.bold(String(ee.length))}`),c.log(` Tables to delete: ${l.bold(String(T.length))}`),c.log(` GQL permissions to set: ${l.bold(String(ne.length))}`),c.log(` GQL permissions to delete: ${l.bold(String(ie.length))}`),c.newline(),w.length+ee.length+T.length+ne.length+ie.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.`),T.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(),v!==null&&t<v?(c.warn(`Migrations ${P(t+1)}–${P(v)} 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()):v!==null&&t>v&&(c.warn(`Moving the migration label forwards (${P(v)} → ${P(t)}): migrate.ts scripts for migrations ${P(v+1)}–${P(t)} will not run on the next deploy.`),c.newline()),!e.yes){if(!await z.confirm({message:`Continue and set migration label to ${P(t)}?`,default:!1})){c.info(`Operation cancelled.`);return}c.newline()}let ae=y(u,f),manifestFor=e=>{let t=ae.get(e);if(!t)throw Error(`Internal error: no manifest generated for table "${e}". No changes were applied.`);return t},oe=w.map(e=>manifestFor(e)),se=ee.map(e=>manifestFor(e));try{await Promise.all([...oe.map(e=>m.createTailorDBType({workspaceId:h,namespaceName:o.namespace,tailordbType:e})),...se.map(e=>m.updateTailorDBType({workspaceId:h,namespaceName:o.namespace,tailordbType:e}))])}catch(e){Nt(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(ne.map(({typeName:e,permission:t})=>{let n={workspaceId:h,namespaceName:o.namespace,typeName:e,permission:t};return D.has(e)?m.updateTailorDBGQLPermission(n):m.createTailorDBGQLPermission(n)})),await Promise.all(ie.map(e=>m.deleteTailorDBGQLPermission({workspaceId:h,namespaceName:o.namespace,typeName:e.typeName}))),await Promise.all(T.map(e=>m.deleteTailorDBType({workspaceId:h,namespaceName:o.namespace,tailordbTypeName:e}))),await tn(m,{trn:_,labels:{[ut]:Vt(t),...u.rebaseline?.historyId?{[d]:u.rebaseline.historyId}:{}},remove:u.rebaseline?.historyId?void 0:[d]}),c.success(`Synced namespace ${l.bold(o.namespace)} to migration ${l.bold(P(t))}.`),t<s&&(c.newline(),c.info(`Run 'tailor deploy' to apply migrations ${P(t+1)}–${P(s)} from the working tree.`))}const ra=N({name:`sync`,description:`Sync remote TailorDB schema to a specific migration snapshot (recovery from --no-schema-check drift).`,args:q.strictObject({...L,...O,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 R({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`?Error(`Seed data directory not found: ${e}. Run 'tailor generate' before testing migrations.`,{cause:t}):t}if(!t.isDirectory())throw Error(`Seed data path is not a directory: ${e}`)}function assertAssertionScript(e){let t=U.resolve(e),n;try{n=Y.statSync(t)}catch(e){throw e.code===`ENOENT`?Error(`Migration assertion script not found: ${t}`,{cause:e}):e}if(!n.isFile())throw Error(`Migration assertion path is not a file: ${t}`)}function assertCloneTargetRegion(e,t){if(e!==t)throw Error(`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 Error(`The migration test target workspace must differ from the source workspace.`)}function resolveAssertionNamespace(e,t){let n=t??(e.length===1?e[0]:void 0);if(!n)throw Error(`--assert-namespace is required when pending migrations span multiple namespaces.`);if(!e.includes(n))throw Error(`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=>It(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 Error(`Application data clone failed: ${i.errorMessage||`unknown platform error`}`);if(i.status!==r.PENDING&&i.status!==r.PROCESSING)throw Error(`Application data clone returned unexpected status ${i.status}.`);await delay(n)}throw Error(`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=U.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(`
93
- `).map((e,n)=>{let r;try{r=JSON.parse(e)}catch(e){throw Error(`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 Error(`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)}-${Cr(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=S(r.config,U.dirname(r.config.path)),a=r.application.tailorDBServices.map(ht),o=(await Xe(e.client,n,i,r.config,a)).find(e=>e.hasDrift||e.checkpointMissingLocal||e.checkpointRepair);if(o)throw Error(`Source namespace "${o.namespace}" changed after migration test preparation. Run the migration test again.`);for(let r of i){let i=t.baselines.get(r.namespace);if(!i)continue;let a=await Me(e.client,I(n,`tailordb`,r.namespace));if(a!==i.migrationNumber)throw Error(`Source namespace "${r.namespace}" moved from migration ${i.migrationNumber} to ${a??`none`} after migration test preparation. 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 It(e.client,n,r.namespace);if(tt(i,a).changes.length>0)throw Error(`Source namespace "${r.namespace}" schema changed after migration test preparation. 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 kn(()=>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 Error(`Auth configuration is required to execute migration test scripts.`);let i=n??en(migrationConfig(e.loaded,t),r.config.machineUsers?Object.keys(r.config.machineUsers):void 0);if(!i)throw Error(`No machine user is available for namespace "${t}". 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 ln({configPath:e.configPath}),n=U.dirname(t.config.path),r=S(t.config,n);if(r.length===0)throw Error(`No TailorDB services with migrations configuration found.`);for(let e of r)E(e.migrationsDir,e.namespace);let i;e.data===`seed`&&(i=await me({configPath:t.config.path}),assertSeedDataDirectory(U.join(i.distPath,`data`))),e.assertionPath&&assertAssertionScript(e.assertionPath);let a=t.application.tailorDBServices.map(ht),s=await C({profile:e.profile}),c=await wt({profile:e.profile}),l=await B(s,c),u=await A({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 Xe(l,u,r,t.config,a),_=g.find(e=>e.hasDrift||e.checkpointMissingLocal);if(_)throw Error(`Source namespace "${_.namespace}" does not match its migration checkpoint. Run 'tailor tailordb migration validate' first.`);let v=g.find(e=>e.checkpointRepair);if(v)throw Error(`Source namespace "${v.namespace}" has a pending migration checkpoint repair. Run 'tailor deploy' against the source workspace first.`);let y=new Map,b=new Map,x=[];for(let e of r){let t=await Me(l,I(u,`tailordb`,e.namespace));if(t===null)throw Error(`Source namespace "${e.namespace}" has no sdk-migration checkpoint. Deploy or set its migration checkpoint before testing.`);let n=ue(e.migrationsDir);if(t>n)throw Error(`Source namespace "${e.namespace}" is at migration ${t}, but the local history ends at ${n}.`);let r=k(e.migrationsDir,t);if(!r)throw Error(`No migration baseline snapshot found for namespace "${e.namespace}".`);y.set(e.namespace,{migrationNumber:t,snapshot:r,historyId:r.rebaseline?.historyId??null});let i=k(e.migrationsDir,n);if(!i)throw Error(`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 Error(`No pending TailorDB migrations found in the source workspace.`);let w=await createMigrationTestBaselineSnapshots({client:l,workspaceId:u,dataMode:e.data,inputs:a,baselines:y}),ee={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:w,targetSnapshots:b,pendingNamespaces:x,...h?{designatedTarget:{id:h.id,region:h.region}}:{}};return{state:{client:l,loaded:t,options:e,...i?{seedContext:i}:{}},prepared:ee}}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 et(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 lt({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 un(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=U.join(i.distPath,`data`);assertSeedDataDirectory(a);let s=new Map(r.loaded.application.tailorDBServices.map(e=>{let n=t.baselines.get(e.namespace),r=ht(e);return[e.namespace,n?.snapshot??Wt({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 we(e,l,U.dirname(r.loaded.config.path)),d=ve({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 Pe({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 Error(i.error??`Seed execution failed for namespace "${e}".`);if(JSON.parse(i.result||`{}`).success!==!0)throw Error(`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?Error(`Application data clone is not enabled for this platform. Retry with '--data seed'.`,{cause:e}):e}if(!o)throw Error(`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 qt({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 cn(r,s,0,o.loaded.config.env??{},U.dirname(o.loaded.config.path)),u=await Pe({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 Error(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 Error(`--target-workspace-id requires --yes because the target may be overwritten.`);if(e.keep&&e.targetWorkspaceId)throw Error(`--keep applies only to automatically created workspaces; a designated target is always retained.`);if(e.assertionNamespace&&!e.assertionPath)throw Error(`--assert is required when --assert-namespace is provided.`);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(e){if(!s)throw Error(`Failed to delete temporary workspace ${i.id}: ${e instanceof Error?e.message:String(e)}`,{cause:e});c.warn(`Failed to delete temporary workspace ${i.id}: ${e instanceof Error?e.message:String(e)}`)}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){g(`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 ia=N({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({...L,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 R({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 We(e)){if(t.type!==`diff`)continue;let n=Je(t.path),s=ce(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 Error(`Migration(s) ${r.map(P).join(`, `)} in namespace "${t}" require a migration script but have no migrate.ts. 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=>` ${rt({migrationNumber:e,namespace:t,configPath:n})}`).join(`
94
- `);throw Error(`Migration(s) ${i.map(P).join(`, `)} in namespace "${t}" have both a --no-script skip acknowledgment and migrate.ts. Clear the stale acknowledgment(s):
95
- ${e}\nOr delete migrate.ts to keep the skip.`)}if(a.length>0)throw Error(`Migration(s) ${a.map(P).join(`, `)} in namespace "${t}" contain generated normalization logic that still requires review in migrate.ts. Review each ${Oe} 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.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 M(e.configPath),r=U.dirname(t.path),i=S(t,r);if(i.length===0)throw Error(`No TailorDB services with migrations configuration found`);let a=e.namespace?i.filter(t=>t.namespace===e.namespace):i;if(a.length===0)throw Error(`Namespace "${e.namespace}" not found or does not have migrations configured`);let o=n.length>0?new Zt(n):void 0,{defineApplication:s}=await import(`../application-B4tCGHiQ.mjs`),c=s({config:t,pluginManager:o});for(let e of c.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();Bn({tailorDBServices:c.tailorDBServices});for(let{namespace:e}of a)if(!c.tailorDBServices.some(t=>t.namespace===e))throw Error(`No TailorDB service found for namespace "${e}"`);let l=c.tailorDBServices.map(ht),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{E(t.migrationsDir,t.namespace),k(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,e instanceof Error?e.message:String(e))}let m={targetNamespaces:a,migrationFileErrors:d,localResults:await ft(u,f),...p?{unacknowledgedWarnings:p}:{}};if(f.length===0)return{reports:buildValidationReports(m)};let h;try{let n=await C({profile:e.profile}),r=await B(n),i=await A({workspaceId:e.workspaceId,profile:e.profile});h=await Xe(r,i,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: ${l.bold(t.namespace)}`),!t.migrationFiles.valid){c.log(` Migration files: ${l.error(`invalid`)}`),c.log(` ${t.migrationFiles.error}`);continue}c.log(` Migration files: ${l.success(`OK`)}`);let e=t.localSchema;e?.hasDiff?e.diff?(c.log(` Local schema: ${l.error(`changes not in migration files`)}`),c.log(` ${Qt(e.diff)}`),c.log(st(e.diff))):c.log(` Local schema: ${l.error(`no migration snapshot found`)}`):c.log(` Local schema: ${l.success(`OK`)}`);let n=t.remoteSchema;n?.skipped===`check_failed`?c.log(` Remote schema: ${l.error(`not checked`)}`):n?.checkpointRepair?c.log(` Remote schema: ${l.success(`OK`)} (next deploy will reset the checkpoint to 0000 from ${P(n.checkpointRepair.from)})`):n?.checkpointMissingLocal?c.log(` Remote schema: ${l.error(`remote migration ${P(n.remoteMigrationNumber)} is not in the local migration history`)}`):n?.hasDrift?(c.log(` Remote schema: ${l.error(`drift detected`)} (remote migration: ${P(n.remoteMigrationNumber)})`),c.log(he(n.drifts))):n?.skipped===`not_deployed`?c.log(` Remote schema: ${l.dim(`skipped (namespace not deployed)`)}`):n?.skipped===`no_migration_label`?c.log(` Remote schema: ${l.dim(`skipped (deployed namespace has no migration state)`)}`):n?.skipped===`no_snapshot`?c.log(` Remote schema: ${l.dim(`skipped (no local snapshot for remote migration ${P(n.remoteMigrationNumber)})`)}`):n&&c.log(` Remote schema: ${l.success(`OK`)} (remote migration: ${P(n.remoteMigrationNumber)})`);let r=t.warningAcknowledgments;if(r){if(r.valid)c.log(` Warning acknowledgments: ${l.success(`OK`)}`);else{c.log(` Warning acknowledgments: ${l.error(`missing for pending migration(s) with possible data loss`)}`);for(let e of r.missing){let t=P(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 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.`),e.some(e=>e.remoteSchema?.checkpointMissingLocal)&&c.info(`The remote migration checkpoint is ahead of the local history. Pull the latest migration files, or run 'tailor tailordb migration status' to compare.`),e.some(e=>e.remoteSchema?.hasDrift)&&vt(e.map(e=>({hasDrift:e.remoteSchema?.hasDrift??!1,drifts:e.remoteSchema?.drifts??[]})));let n=e.filter(e=>e.warningAcknowledgments&&!e.warningAcknowledgments.valid);if(n.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 n)for(let n of e.warningAcknowledgments?.missing??[])c.info(` ${rt({migrationNumber:n.migrationNumber,namespace:e.namespace,configPath:t,noScript:!0})}`,{mode:`plain`})}}async function validate(e){g(`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 Error(`Migration validation failed for ${r} namespace(s)`)}const aa=N({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({...L,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})}}),oa=G({name:`migration`,description:`Manage TailorDB schema migrations.`,subCommands:{generate:oe,rebaseline:ea,script:fe,set:ta,status:na,sync:ra,test:ia,validate:aa}}),sa=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:St,migration:oa}}),ca=N({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-CqbQXFDp.mjs`);await n({from:e.from,dryRun:e[`dry-run`],path:U.resolve(e.path)})}}),la=N({name:`current`,description:`Show current user.`,args:q.strictObject({}),run:async()=>{let e=await D(),t=process.env.TAILOR_PLATFORM_PROFILE,n=t?e.profiles[t]:void 0;if(t&&!n)throw Error(`Profile "${t}" not found`);let r=n?j(n):void 0,i=t?n?.user??null:e.current_user,a=c.jsonMode;if(!i)throw Error(H`
91
+ `),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)}}),Ii=w({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 B(),n=t.profiles[e.name];if(!n)throw Error(`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 Error(`Please provide at least one property to 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`]===``?Pe(n):h;if((e[`machine-user`]!==void 0||e[`machine-user-override`]!==void 0)&&u===`deny`&&!l)throw e[`machine-user-override`]===`deny`?Error(`--machine-user-override deny requires --machine-user.`):Error(`Cannot clear the machine user while machine-user-override is "deny". Also pass --machine-user-override allow.`);if(e.user!==void 0||e[`workspace-id`]!==void 0||e[`platform-url`]!==void 0){let e=await S(t,i,g);s=e.user;let n=await kn(e.accessToken,h);if(!(await jn(async(e,t)=>{let{workspaces:r,nextPageToken:i}=await n.listWorkspaces({pageToken:e,pageSize:t});return[r,i]})).find(e=>e.id===o))throw Error(`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`]),k(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(_)}}),Li=G({name:`profile`,description:`Manage workspace profiles (user + workspace combinations).`,subCommands:{create:Ni,delete:Pi,list:Fi,update:Ii},async run(){await K(Fi,[])}}),Ri={"vault-name":W(q.string(),{alias:`V`,description:`Vault name`})},zi={...Ri,name:W(q.string(),{alias:`n`,description:`Secret name`})},Bi={...zi,value:W(q.string(),{alias:`v`,description:`Secret value`})};async function checkVaultManaged(e){let{client:t,workspaceId:n,vaultName:r}=e,i=M(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[on]}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:[on,mn,Qe]}),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 Vi=w({name:`create`,description:`Create a secret in a vault.`,args:q.strictObject({...N,...Bi,...A}),run:async e=>{await R({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 z.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 Error(`Vault "${e[`vault-name`]}" not found.`,{cause:t});if(t.code===Z.AlreadyExists)throw Error(`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`]}`)}}}),Hi=w({name:`delete`,description:`Delete a secret in a vault.`,args:q.strictObject({...N,...zi,...A}),run:async e=>{await R({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 z.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?Error(`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=F(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 Ui=w({name:`list`,description:`List all secrets in a vault.`,args:q.strictObject({...N,...Ri,...I()}),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?Error(`Vault "${e[`vault-name`]}" not found.`,{cause:t}):t}}}),Wi=w({name:`update`,description:`Update a secret in a vault.`,args:q.strictObject({...N,...Bi,...A}),run:async e=>{await R({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 z.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?Error(`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`]}`)}}}),Gi={name:W(q.string(),{positional:!0,description:`Vault name`})},Ki=w({name:`create`,description:`Create a new Secret Manager vault.`,args:q.strictObject({...N,...Gi}),run:async e=>{await R({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?Error(`Vault "${e.name}" already exists.`,{cause:t}):t}c.success(`Vault: ${e.name} created`)}}),qi=w({name:`delete`,description:`Delete a Secret Manager vault.`,args:q.strictObject({...N,...Gi,...A}),run:async e=>{await R({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 z.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?Error(`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=F(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 Ji=w({name:`list`,description:`List all Secret Manager vaults in the workspace.`,args:q.strictObject({...N,...I()}),run:async e=>{let t=await vaultList({workspaceId:e[`workspace-id`],profile:e.profile,order:e.order,limit:e.limit});c.out(t)}}),Yi=G({name:`vault`,description:`Manage Secret Manager vaults.`,subCommands:{create:Ki,delete:qi,list:Ji},async run(){await K(Ji,[])}}),Xi=G({name:`secret`,description:`Manage Secret Manager vaults and secrets.`,subCommands:{vault:Yi,create:Vi,update:Wi,list:Ui,delete:Hi},async run(){await K(Yi,[])}}),Zi={[t.UNSPECIFIED]:`unspecified`,[t.PENDING]:`pending`,[t.VERIFYING]:`verifying`,[t.CERT_ISSUED]:`cert_issued`,[t.ACTIVE]:`active`,[t.FAILED]:`failed`},Qi=w({name:`get`,description:`Get details of a custom domain.`,args:q.strictObject({...N,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 Error(r);let a={domain:i.domain,status:Zi[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?Error(r,{cause:e}):e}}}),$i=w({name:`list`,description:`List custom domains for a static website.`,args:q.strictObject({...N,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:Zi[e.status]??`unknown`,trafficCnameTarget:e.trafficCnameTarget,certificateCnameTarget:e.certificateCnameTarget}));c.out(i)}catch(t){throw t instanceof Q&&t.code===Z.NotFound?Error(`Static website "${e.name}" not found.`,{cause:t}):t}}}),ea=G({name:`domain`,description:`Manage custom domains for static websites.`,subCommands:{list:$i,get:Qi}}),ta=w({name:`get`,description:`Get details of a specific static website.`,args:q.strictObject({...N,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 Error(r);let a={workspaceId:n,name:i.name,description:i.description,url:i.url,allowedIpAddresses:e.json?i.allowedIpAddresses:i.allowedIpAddresses.join(`
92
+ `)};c.out(a)}catch(e){throw e instanceof Q&&e.code===Z.NotFound?Error(r,{cause:e}):e}}});async function listStaticWebsites(e){let{client:t,workspaceId:n}=await D({profile:e?.profile,workspaceId:e?.workspaceId}),r=F(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 na=w({name:`list`,description:`List all static websites in a workspace.`,args:q.strictObject({...N,...I()}),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)}}),ra=G({name:`staticwebsite`,description:`Manage static websites in your workspace.`,subCommands:{deploy:Be,domain:ea,list:na,get:ta},async run(){await K(na,[])}}),ia=new Set(Object.values(Ue));async function activateBaseline(e,t,n,r){let i=await $.realpath(e),a=U.dirname(i),o=U.basename(i),s=await $.mkdtemp(U.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()||!se.test(e.name))continue;let t=U.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:5,createdAt:new Date().toISOString(),rebaseline:r},a=await gn(e,s,0);mt(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){g(`tailordb migration`);let{config:t,plugins:n}=await O(e.configPath),r=U.dirname(t.path),i=m(P(t,r),e.namespace),a=tr({command:`tailor`,args:[`tailordb`,`migration`,`generate`,`--config`,t.path]});T(i.migrationsDir,i.namespace);let o=E(i.migrationsDir);if(!o)throw Error(`No migration history found for namespace "${i.namespace}". Run ${a} first.`);let s=pe(i.migrationsDir),u=E(i.migrationsDir,0)?.rebaseline?.historyId??null,d=be([i])[i.namespace],f=n.length>0?new gt(n):void 0,{defineApplication:p}=await import(`../application-BFTkaW6X.mjs`),h=p({config:t,pluginManager:f});for(let e of h.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let _=h.tailorDBServices.find(e=>e.namespace===i.namespace);if(!_)throw Error(`No TailorDB service found for namespace "${i.namespace}"`);let assertLocalTypesReady=()=>{let e=ie(_.types,i.namespace),t=Bt(o,e.tables,i.namespace);if(Ft(t))throw c.error(`Migration history does not reproduce the current local schema for namespace ${l.bold(i.namespace)}:`),c.log(Vt(t)),Error(`Refusing to re-baseline: the migration history must reproduce the current local schema. Run ${a} first.`)},localSourceFiles=()=>[t.path,...Kn(_.config,r)];assertLocalTypesReady();let v=Et(localSourceFiles()),{client:y,workspaceId:b}=await D({profile:e.profile,workspaceId:e.workspaceId}),x=[`--config`,t.path,`--workspace-id`,b,...e.profile?[`--profile`,e.profile]:[]],ee=tr({command:`tailor`,args:[`tailordb`,`migration`,`set`,`0`,`--namespace`,i.namespace,...x]}),S=tr({command:`tailor`,args:[`deploy`,...x]}),assertConnectedWorkspaceReady=async(e,n)=>{let r=await Oe(y,M(b,`tailordb`,i.namespace)),a=r.number;if(a!==s){let e=a===null?`<unset>`:L(a);throw Error(`The connected workspace must be at the latest migration ${L(s)} before re-baselining; current checkpoint is ${e}.`)}if(r.historyIdInvalid)throw Error(`Refusing to re-baseline: the connected workspace has an invalid migration history marker.`);if(r.historyId!==e)throw Error(n===`confirmation`?`The connected workspace migration history changed while waiting for confirmation. Run the command again.`:`Refusing to re-baseline: the connected workspace does not match the local migration history.`);let o=await pn(y,b,[i],t,[an(_)]),l=o[0];if(!l||l.remoteMigrationNumber!==s||l.hasDrift||l.checkpointMissingLocal)throw l?.hasDrift&&(c.error(`Remote schema drift detected:`),c.log(yt(o))),Error(`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 ${l.bold(i.namespace)}.`),c.log(` Latest migration: ${L(s)}`),c.log(` New history: 0000/schema.json only`),c.log(` migrate.ts and db.ts files will disappear from the working tree.`),c.log(` Committed migration files will remain in Git history. Preserve any uncommitted files before continuing.`),c.log(` Every other environment must already be at the latest migration.`),c.log(` The connected workspace checkpoint will be reset to 0000.`),c.newline(),!e.yes&&!await z.confirm({message:`Re-baseline this migration history and reset the connected workspace checkpoint?`,default:!1})){c.info(`Operation cancelled.`);return}if(T(i.migrationsDir,i.namespace),be([i])[i.namespace]!==d)throw Error(`Migration files changed while waiting for confirmation. Run the command again.`);if(Et(localSourceFiles())!==v)throw Error(`Local TailorDB table or config files changed. Run the command again.`);assertLocalTypesReady(),await assertConnectedWorkspaceReady(u,`confirmation`);let C={historyId:qt(),replacedHistoryId:u,replacedLatestMigration:s};await activateBaseline(i.migrationsDir,o,i.namespace,C);try{await dn(y,b,i.namespace,0,C.historyId)}catch(e){throw Error(`The local migration history was re-baselined, but the connected workspace checkpoint could not be updated. Run ${ee}, or run ${S} with schema checks enabled after resolving the connection error.`,{cause:e})}c.success(`Re-baselined ${l.bold(i.namespace)} and reset the connected workspace checkpoint to 0000.`)}const aa=w({name:`rebaseline`,description:`Collapse the full migration history into a new 0000 baseline.`,notes:`Re-baselining removes migrations after 0000 from the working tree, records a new migration history ID, and resets the connected workspace checkpoint without changing its schema or data. Every environment must already have applied the latest migration before you run this command.`,args:q.strictObject({...j,...A,namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await R({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){g(`tailordb migration`);let t=ut(e.number),{config:n}=await O(e.configPath),r=U.dirname(n.path),i=P(n,r),a=m(i,e.namespace),o=a.namespace;T(a.migrationsDir,o),Wt(a.migrationsDir,t);let s=E(a.migrationsDir,0)?.rebaseline?.historyId,{client:u,workspaceId:d}=await D({profile:e.profile,workspaceId:e.workspaceId}),f=M(d,`tailordb`,o),p=await Oe(u,f),h=p.number,_=h??0,v=p.historyIdInvalid?`<invalid>`:p.historyId??`<unset>`,y=s??`<unset>`;if(c.newline(),c.warn(`This operation will change TailorDB migration state metadata.`),c.log(`Namespace: ${l.bold(o)}`),c.log(`Current migration: ${h===null?`<unset>`:l.bold(L(h))}`),c.log(`New migration: ${l.bold(L(t))}`),c.log(`Current migration history ID: ${l.bold(v)}`),c.log(`New migration history ID: ${l.bold(y)}`),c.newline(),t<_?(c.warn(`Setting migration number backwards (${L(_)} → ${L(t)}) will cause previous migrations to be re-executed on next apply.`),c.newline()):t>_&&(c.warn(`Setting migration number forwards (${L(_)} → ${L(t)}) will skip migrations ${L(_+1)} to ${L(t)}.`),c.newline()),!e.yes){if(!await z.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:{[Rt]:nt(t),...s?{[en]:s}:{}},remove:s?void 0:[en]}),c.success(`Migration checkpoint set to ${l.bold(L(t))} for namespace ${l.bold(o)}`)}const oa=w({name:`set`,description:`Set migration checkpoint to a specific number.`,notes:"The migration number must be a 4-digit value (e.g. `0001`) or a bare integer (e.g. `1`) within 0–9999, and must exist in the local migration history; `0` is always accepted as the baseline, provided the local history passes validation. A gapped history is rejected.\n\nMetadata lookup failures (authentication, permission, or network errors) are reported as errors; only a not-yet-deployed namespace is treated as having no checkpoint.",args:q.strictObject({...j,...A,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 R({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 O(e.configPath),n=U.dirname(t.path),r=P(t,n);if(r.length===0)throw Error(`No TailorDB services with migrations configuration found`);let i=e.namespace?r.filter(t=>t.namespace===e.namespace):r;if(i.length===0)throw Error(`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=Xe(t),r=new Map,i=null;for(let e of n){if(e.type===`schema`){let t=mt(e.path);e.number===0&&(i=t.rebaseline?.historyId??null);continue}try{let t=d(e.path);t.description&&r.set(e.number,t.description)}catch(e){if(e instanceof lt)throw e}}a.set(e,{migrationFiles:n,descriptions:r,historyId:i})}catch(t){o.set(e,t instanceof Error?t.message:String(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=M(c,`tailordb`,e),d;try{d=await Oe(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:L(e),...r.has(e)?{description:r.get(e)}:{}}));l.push({status:`ok`,namespace:e,currentMigration:f,currentMigrationLabel:L(f),pendingMigrations:p})}return l}function printMigrationStatuses(e){for(let t of e){if(c.newline(),c.info(`Namespace: ${l.bold(t.namespace)}`),isStatusFailure(t)){c.error(` Migration status error: ${t.error}`);continue}if(c.log(` Current migration: ${l.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){g(`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 Error(`Migration status check failed for ${n.length} namespace${n.length===1?``:`s`}: ${e}`)}}const sa=w({name:`status`,description:`Show the current migration status for TailorDB namespaces, including applied and pending migrations.`,notes:`Every local migration file is checked for a compatible format version, and deployed migration history IDs must match the local baseline. Compatibility errors, history mismatches, and metadata lookup failures are reported per namespace and make the command exit non-zero; only a not-yet-deployed namespace is treated as having no applied migrations.`,args:q.strictObject({...j,namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (shows all namespaces if not specified)`})}),run:async e=>{await status({configPath:e.config,namespace:e.namespace,workspaceId:e[`workspace-id`],profile:e.profile,json:c.jsonMode})}});async function fetchRemoteGqlPermissions(e,t,n){return wn(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?Error(`Cannot sync: TailorDB namespace "${n}" has not been deployed yet.`,{cause:e}):e}})}async function assertMigrationsReproduceLocalTypes(e,t){let{config:n,plugins:r}=e,i=r.length>0?new gt(r):void 0,{defineApplication:a,generatePluginFilesIfNeeded:o}=await import(`../application-BFTkaW6X.mjs`),s=a({config:n,pluginManager:i}),u=s.tailorDBServices.find(e=>e.namespace===t.namespace);if(!u)throw Error(`No TailorDB service found for namespace "${t.namespace}"`);for(let e of s.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let d=o(i,s.tailorDBServices,n.path),f=s.executorService??(d.length>0?(await import(`../service-CmwD9bwv.mjs`)).createExecutorService({config:{files:[]},baseDir:U.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??{}))St(e)&&e.trigger.kind===`tailordb`&&p.add(e.trigger.tableName);let m={executorUsedTables:p,namespaceGqlOperations:u.config.gqlOperations},h=E(t.migrationsDir);if(!h)return m;let g=ie(u.types,t.namespace),_=Bt(h,g.tables,t.namespace);if(!Ft(_))return m;throw c.error(`Migration history does not reproduce the current local schema for namespace ${l.bold(t.namespace)}:`),c.log(Vt(_)),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(),Error(`Refusing to sync: the migration history must reproduce the current local schema before it can be applied to the remote.`)}async function sync(e){g(`tailordb migration`);let t=ut(e.number),n=await O(e.configPath),{config:r}=n,i=U.dirname(r.path),a=P(r,i),o=m(a,e.namespace);T(o.migrationsDir,o.namespace);let s=Wt(o.migrationsDir,t),u=E(o.migrationsDir,t);if(!u)throw Error(`No initial schema snapshot found in ${o.migrationsDir}. Expected 0000/schema.json.`);let d=await assertMigrationsReproduceLocalTypes(n,o),{client:f,workspaceId:p}=await D({profile:e.profile,workspaceId:e.workspaceId}),h=M(p,`tailordb`,o.namespace),_=await ee(f,h),v=await fetchRemoteTypes(f,p,o.namespace),y=new Set(v.map(e=>e.name)),{creates:b,updates:x,deletes:S}=cn(u,y),C=await fetchRemoteGqlPermissions(f,p,o.namespace),te=new Set(C.map(e=>e.typeName)),re=Object.entries(u.tables).flatMap(([e,t])=>t.permissions?.gql?[{typeName:e,permission:ne(t.permissions.gql)}]:[]),ie=new Set(re.map(e=>e.typeName)),ae=C.filter(e=>!ie.has(e.typeName));if(c.newline(),c.info(`Namespace: ${l.bold(o.namespace)}`),c.log(` Current migration: ${_===null?`<unset>`:l.bold(L(_))}`),c.log(` Target migration: ${l.bold(L(t))}`),c.log(` Tables to create: ${l.bold(String(b.length))}`),c.log(` Tables to update: ${l.bold(String(x.length))}`),c.log(` Tables to delete: ${l.bold(String(S.length))}`),c.log(` GQL permissions to set: ${l.bold(String(re.length))}`),c.log(` GQL permissions to delete: ${l.bold(String(ae.length))}`),c.newline(),b.length+x.length+S.length+re.length+ae.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(),_!==null&&t<_?(c.warn(`Migrations ${L(t+1)}–${L(_)} 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()):_!==null&&t>_&&(c.warn(`Moving the migration label forwards (${L(_)} → ${L(t)}): migrate.ts scripts for migrations ${L(_+1)}–${L(t)} will not run on the next deploy.`),c.newline()),!e.yes){if(!await z.confirm({message:`Continue and set migration label to ${L(t)}?`,default:!1})){c.info(`Operation cancelled.`);return}c.newline()}let oe=Le(u,d),manifestFor=e=>{let t=oe.get(e);if(!t)throw Error(`Internal error: no manifest generated for table "${e}". No changes were applied.`);return t},se=b.map(e=>manifestFor(e)),w=x.map(e=>manifestFor(e));try{await Promise.all([...se.map(e=>f.createTailorDBType({workspaceId:p,namespaceName:o.namespace,tailordbType:e})),...w.map(e=>f.updateTailorDBType({workspaceId:p,namespaceName:o.namespace,tailordbType:e}))])}catch(e){wt(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(re.map(({typeName:e,permission:t})=>{let n={workspaceId:p,namespaceName:o.namespace,typeName:e,permission:t};return te.has(e)?f.updateTailorDBGQLPermission(n):f.createTailorDBGQLPermission(n)})),await Promise.all(ae.map(e=>f.deleteTailorDBGQLPermission({workspaceId:p,namespaceName:o.namespace,typeName:e.typeName}))),await Promise.all(S.map(e=>f.deleteTailorDBType({workspaceId:p,namespaceName:o.namespace,tailordbTypeName:e}))),await at(f,{trn:h,labels:{[Rt]:nt(t),...u.rebaseline?.historyId?{[en]:u.rebaseline.historyId}:{}},remove:u.rebaseline?.historyId?void 0:[en]}),c.success(`Synced namespace ${l.bold(o.namespace)} to migration ${l.bold(L(t))}.`),t<s&&(c.newline(),c.info(`Run 'tailor deploy' to apply migrations ${L(t+1)}–${L(s)} from the working tree.`))}const ca=w({name:`sync`,description:`Sync remote TailorDB schema to a specific migration snapshot (recovery from --no-schema-check drift).`,args:q.strictObject({...j,...A,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 R({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`?Error(`Seed data directory not found: ${e}. Run 'tailor generate' before testing migrations.`,{cause:t}):t}if(!t.isDirectory())throw Error(`Seed data path is not a directory: ${e}`)}function assertAssertionScript(e){let t=U.resolve(e),n;try{n=Y.statSync(t)}catch(e){throw e.code===`ENOENT`?Error(`Migration assertion script not found: ${t}`,{cause:e}):e}if(!n.isFile())throw Error(`Migration assertion path is not a file: ${t}`)}function assertCloneTargetRegion(e,t){if(e!==t)throw Error(`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 Error(`The migration test target workspace must differ from the source workspace.`)}function resolveAssertionNamespace(e,t){let n=t??(e.length===1?e[0]:void 0);if(!n)throw Error(`--assert-namespace is required when pending migrations span multiple namespaces.`);if(!e.includes(n))throw Error(`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=>xt(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 Error(`Application data clone failed: ${i.errorMessage||`unknown platform error`}`);if(i.status!==r.PENDING&&i.status!==r.PROCESSING)throw Error(`Application data clone returned unexpected status ${i.status}.`);await delay(n)}throw Error(`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=U.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(`
93
+ `).map((e,n)=>{let r;try{r=JSON.parse(e)}catch(e){throw Error(`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 Error(`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)}-${Dr(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=P(r.config,U.dirname(r.config.path)),a=r.application.tailorDBServices.map(an),o=(await pn(e.client,n,i,r.config,a)).find(e=>e.hasDrift||e.checkpointMissingLocal||e.checkpointRepair);if(o)throw Error(`Source namespace "${o.namespace}" changed after migration test preparation. Run the migration test again.`);for(let r of i){let i=t.baselines.get(r.namespace);if(!i)continue;let a=await ee(e.client,M(n,`tailordb`,r.namespace));if(a!==i.migrationNumber)throw Error(`Source namespace "${r.namespace}" moved from migration ${i.migrationNumber} to ${a??`none`} after migration test preparation. 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 xt(e.client,n,r.namespace);if(Xt(i,a).changes.length>0)throw Error(`Source namespace "${r.namespace}" schema changed after migration test preparation. 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 Nn(()=>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 Error(`Auth configuration is required to execute migration test scripts.`);let i=n??it(migrationConfig(e.loaded,t),r.config.machineUsers?Object.keys(r.config.machineUsers):void 0);if(!i)throw Error(`No machine user is available for namespace "${t}". 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 fn({configPath:e.configPath}),n=U.dirname(t.config.path),r=P(t.config,n);if(r.length===0)throw Error(`No TailorDB services with migrations configuration found.`);for(let e of r)T(e.migrationsDir,e.namespace);let i;e.data===`seed`&&(i=await ye({configPath:t.config.path}),assertSeedDataDirectory(U.join(i.distPath,`data`))),e.assertionPath&&assertAssertionScript(e.assertionPath);let a=t.application.tailorDBServices.map(an),s=await h({profile:e.profile}),c=await ae({profile:e.profile}),l=await kn(s,c),u=await ve({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 g=p?o(p.workspace,`target workspace "${e.targetWorkspaceId}" not found`):void 0,_=await pn(l,u,r,t.config,a),v=_.find(e=>e.hasDrift||e.checkpointMissingLocal);if(v)throw Error(`Source namespace "${v.namespace}" does not match its migration checkpoint. Run 'tailor tailordb migration validate' first.`);let y=_.find(e=>e.checkpointRepair);if(y)throw Error(`Source namespace "${y.namespace}" has a pending migration checkpoint repair. Run 'tailor deploy' against the source workspace first.`);let b=new Map,x=new Map,S=[];for(let e of r){let t=await ee(l,M(u,`tailordb`,e.namespace));if(t===null)throw Error(`Source namespace "${e.namespace}" has no sdk-migration checkpoint. Deploy or set its migration checkpoint before testing.`);let n=pe(e.migrationsDir);if(t>n)throw Error(`Source namespace "${e.namespace}" is at migration ${t}, but the local history ends at ${n}.`);let r=E(e.migrationsDir,t);if(!r)throw Error(`No migration baseline snapshot found for namespace "${e.namespace}".`);b.set(e.namespace,{migrationNumber:t,snapshot:r,historyId:r.rebaseline?.historyId??null});let i=E(e.migrationsDir,n);if(!i)throw Error(`No target migration snapshot found for namespace "${e.namespace}".`);x.set(e.namespace,i),t<n&&S.push(e.namespace)}if(S.length===0)throw Error(`No pending TailorDB migrations found in the source workspace.`);let C=await createMigrationTestBaselineSnapshots({client:l,workspaceId:u,dataMode:e.data,inputs:a,baselines:b}),te={sourceWorkspaceId:u,sourceApplicationName:t.config.name,temporaryWorkspace:{name:temporaryWorkspaceName(),region:m.region,...m.organizationId?{organizationId:m.organizationId}:{},...m.folderId?{folderId:m.folderId}:{}},baselines:b,baselineSnapshots:C,targetSnapshots:x,pendingNamespaces:S,...g?{designatedTarget:{id:g.id,region:g.region}}:{}};return{state:{client:l,loaded:t,options:e,...i?{seedContext:i}:{}},prepared:te}}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 tt(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 pt({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 dn(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=U.join(i.distPath,`data`);assertSeedDataDirectory(a);let s=new Map(r.loaded.application.tailorDBServices.map(e=>{let n=t.baselines.get(e.namespace),r=an(e);return[e.namespace,n?.snapshot??jt({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 Ae(e,l,U.dirname(r.loaded.config.path)),d=Ce({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 Re({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 Error(i.error??`Seed execution failed for namespace "${e}".`);if(JSON.parse(i.result||`{}`).success!==!0)throw Error(`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?Error(`Application data clone is not enabled for this platform. Retry with '--data seed'.`,{cause:e}):e}if(!o)throw Error(`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 $t({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 y(r,s,0,o.loaded.config.env??{},U.dirname(o.loaded.config.path)),u=await Re({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 Error(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 Error(`--target-workspace-id requires --yes because the target may be overwritten.`);if(e.keep&&e.targetWorkspaceId)throw Error(`--keep applies only to automatically created workspaces; a designated target is always retained.`);if(e.assertionNamespace&&!e.assertionPath)throw Error(`--assert is required when --assert-namespace is provided.`);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(e){if(!s)throw Error(`Failed to delete temporary workspace ${i.id}: ${e instanceof Error?e.message:String(e)}`,{cause:e});c.warn(`Failed to delete temporary workspace ${i.id}: ${e instanceof Error?e.message:String(e)}`)}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){g(`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 la=w({name:`test`,description:`Test pending migrations with seed fixtures or cloned data in a temporary workspace.`,notes:`The source workspace is read-only. Without --target-workspace-id, the command creates a workspace in the source workspace's region and deletes it after success or failure; pass --keep to retain it for inspection. A designated target is retained and requires --yes. Clone mode copies TailorDB records only; it does not copy IdP users or file blobs.`,args:q.strictObject({...j,yes:W(q.boolean().default(!1),{alias:`y`,description:`Acknowledge that a designated target workspace may be overwritten`}),data:W(q.enum([`seed`,`clone`]).default(`seed`),{description:`Data source for the migration test (seed or clone)`}),"target-workspace-id":W(q.uuid().optional(),{description:`Existing throwaway workspace to retain after the test (requires --yes)`}),keep:W(q.boolean().default(!1),{description:`Keep the automatically created workspace after the test`}),assert:W(q.string().optional(),{description:`Path to a TypeScript assertion script to run after migrations`,completion:{type:`file`,extensions:[`ts`]}}),"assert-namespace":W(q.string().optional(),{description:`TailorDB namespace exposed to the assertion script`}),"machine-user":W(q.string().optional(),{description:`Machine user for seed and assertion script execution`})}),run:async e=>{await R({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 Xe(e)){if(t.type!==`diff`)continue;let n=d(t.path),s=Ke(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 Error(`Migration(s) ${r.map(L).join(`, `)} in namespace "${t}" require a migration script but have no migrate.ts. 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=>` ${Fe({migrationNumber:e,namespace:t,configPath:n})}`).join(`
94
+ `);throw Error(`Migration(s) ${i.map(L).join(`, `)} in namespace "${t}" have both a --no-script skip acknowledgment and migrate.ts. Clear the stale acknowledgment(s):
95
+ ${e}\nOr delete migrate.ts to keep the skip.`)}if(a.length>0)throw Error(`Migration(s) ${a.map(L).join(`, `)} in namespace "${t}" contain generated normalization logic that still requires review in migrate.ts. Review each ${Ne} 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.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 O(e.configPath),r=U.dirname(t.path),i=P(t,r);if(i.length===0)throw Error(`No TailorDB services with migrations configuration found`);let a=e.namespace?i.filter(t=>t.namespace===e.namespace):i;if(a.length===0)throw Error(`Namespace "${e.namespace}" not found or does not have migrations configured`);let o=n.length>0?new gt(n):void 0,{defineApplication:s}=await import(`../application-BFTkaW6X.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 Error(`No TailorDB service found for namespace "${e}"`);let l=c.tailorDBServices.map(an),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{T(t.migrationsDir,t.namespace),E(t.migrationsDir);let n=assertMigrationScriptsReady(t.migrationsDir,t.namespace,e.configPath);p?.set(t.namespace,n),f.push(t)}catch(e){d.set(t.namespace,e instanceof Error?e.message:String(e))}let m={targetNamespaces:a,migrationFileErrors:d,localResults:await Pt(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 pn(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: ${l.bold(t.namespace)}`),!t.migrationFiles.valid){c.log(` Migration files: ${l.error(`invalid`)}`),c.log(` ${t.migrationFiles.error}`);continue}c.log(` Migration files: ${l.success(`OK`)}`);let e=t.localSchema;e?.hasDiff?e.diff?(c.log(` Local schema: ${l.error(`changes not in migration files`)}`),c.log(` ${_t(e.diff)}`),c.log(Vt(e.diff))):c.log(` Local schema: ${l.error(`no migration snapshot found`)}`):c.log(` Local schema: ${l.success(`OK`)}`);let n=t.remoteSchema;n?.skipped===`check_failed`?c.log(` Remote schema: ${l.error(`not checked`)}`):n?.checkpointRepair?c.log(` Remote schema: ${l.success(`OK`)} (next deploy will reset the checkpoint to 0000 from ${L(n.checkpointRepair.from)})`):n?.checkpointMissingLocal?c.log(` Remote schema: ${l.error(`remote migration ${L(n.remoteMigrationNumber)} is not in the local migration history`)}`):n?.hasDrift?(c.log(` Remote schema: ${l.error(`drift detected`)} (remote migration: ${L(n.remoteMigrationNumber)})`),c.log(je(n.drifts))):n?.skipped===`not_deployed`?c.log(` Remote schema: ${l.dim(`skipped (namespace not deployed)`)}`):n?.skipped===`no_migration_label`?c.log(` Remote schema: ${l.dim(`skipped (deployed namespace has no migration state)`)}`):n?.skipped===`no_snapshot`?c.log(` Remote schema: ${l.dim(`skipped (no local snapshot for remote migration ${L(n.remoteMigrationNumber)})`)}`):n&&c.log(` Remote schema: ${l.success(`OK`)} (remote migration: ${L(n.remoteMigrationNumber)})`);let r=t.warningAcknowledgments;if(r){if(r.valid)c.log(` Warning acknowledgments: ${l.success(`OK`)}`);else{c.log(` Warning acknowledgments: ${l.error(`missing for pending migration(s) with possible data loss`)}`);for(let e of r.missing){let t=L(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 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.`),e.some(e=>e.remoteSchema?.checkpointMissingLocal)&&c.info(`The remote migration checkpoint is ahead of the local history. Pull the latest migration files, or run 'tailor tailordb migration status' to compare.`),e.some(e=>e.remoteSchema?.hasDrift)&&Ze(e.map(e=>({hasDrift:e.remoteSchema?.hasDrift??!1,drifts:e.remoteSchema?.drifts??[]})));let n=e.filter(e=>e.warningAcknowledgments&&!e.warningAcknowledgments.valid);if(n.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 n)for(let n of e.warningAcknowledgments?.missing??[])c.info(` ${Fe({migrationNumber:n.migrationNumber,namespace:e.namespace,configPath:t,noScript:!0})}`,{mode:`plain`})}}async function validate(e){g(`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 Error(`Migration validation failed for ${r} namespace(s)`)}const ua=w({name:`validate`,description:`Validate the full migration history, unreviewed generated migration scripts, and schema drift (local tables vs. migration snapshot, remote schema vs. migration checkpoint) without deploying. This includes the migration and schema-drift checks used by 'deploy' and exits with a non-zero code when issues are found.`,args:q.strictObject({...j,namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (validates all namespaces if not specified)`}),strict:W(q.boolean().default(!1),{description:`Also fail when a pending migration can drop data without an acknowledgment`})}),run:async e=>{await validate({configPath:e.config,namespace:e.namespace,workspaceId:e[`workspace-id`],profile:e.profile,json:c.jsonMode,strict:e.strict})}}),da=G({name:`migration`,description:`Manage TailorDB schema migrations.`,subCommands:{generate:ue,rebaseline:aa,script:_e,set:oa,status:sa,sync:ca,test:la,validate:ua}}),fa=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:Tt,migration:da}}),pa=w({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-CqbQXFDp.mjs`);await n({from:e.from,dryRun:e[`dry-run`],path:U.resolve(e.path)})}}),ma=w({name:`current`,description:`Show current user.`,args:q.strictObject({profile:N.profile}),run:async e=>{let t=await B(),n=e.profile||process.env.TAILOR_PLATFORM_PROFILE,r=n?t.profiles[n]:void 0;if(n&&!r)throw Error(`Profile "${n}" not found`);let i=r?Pe(r):void 0,a=n?r?.user??null:t.current_user,o=c.jsonMode;if(!a)throw Error(H`
96
96
  Current user not set.
97
97
  Please login first using 'tailor login' command to register a user.
98
- `);if(!te(e,i,r))throw Error(H`
99
- Current user '${i}' not found in registered users.
98
+ `);if(!Ot(t,a,i))throw Error(H`
99
+ Current user '${a}' not found in registered users.
100
100
  Please login again using 'tailor login' command to register the user.
101
- `);if(a){c.out({user:i});return}c.out(i)}});function activeCurrentUserKey(e){let t=process.env.TAILOR_PLATFORM_PROFILE;if(!t)return e.current_user?ke(e,e.current_user):null;let n=e.profiles[t];return n?ke(e,n.user,j(n)):null}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 ua=N({name:`list`,description:`List all users.`,args:q.strictObject({}),run:async()=>{let e=await D(),t=c.jsonMode,n=Object.keys(e.users);if(n.length===0){c.info(H`
101
+ `);if(o){c.out({user:a});return}c.out(a)}});function activeCurrentUserKey(e,t){if(!t)return e.current_user?ce(e,e.current_user):null;let n=e.profiles[t];if(!n)throw Error(`Profile "${t}" not found`);return ce(e,n.user,Pe(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 ha=w({name:`list`,description:`List all users.`,args:q.strictObject({profile:N.profile}),run:async e=>{let t=await B(),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`
102
102
  No users found.
103
103
  Please login first using 'tailor login' command to register a user.
104
- `),t&&c.out([]);return}let r=activeCurrentUserKey(e),i=n.map(e=>toUserListInfo(e,r));if(t){c.out([...new Set(i.map(e=>e.user))]);return}i.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)}}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.log(H`
104
+ `),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:ct(e.createdAt),lastUsedAt:ct(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.log(H`
105
105
  Personal access token ${r} successfully.
106
106
 
107
107
  name: ${e}
@@ -109,14 +109,13 @@ ${e}\nOr delete migrate.ts to keep the skip.`)}if(a.length>0)throw Error(`Migrat
109
109
  token: ${t}
110
110
 
111
111
  Please save this token in a secure location. You won't be able to see it again.
112
- `)}function resolvePatUser(e){let t=process.env.TAILOR_PLATFORM_PROFILE;return t?e.profiles[t]?.user??null:e.current_user}async function createPatOperatorClient(){let e=await D(),t=process.env.TAILOR_PLATFORM_PROFILE,n=t?e.profiles[t]:void 0;if(t&&!n)throw Error(`Profile "${t}" not found`);let r=n?j(n):void 0,i=resolvePatUser(e);if(!i)throw Error(`No user logged in.
113
- Please login first using 'tailor login' command.`);let{accessToken:a}=await an(e,i,r);return await B(a,r)}const da=N({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)`})}),run:async e=>{await R();let t=await createPatOperatorClient(),n=getScopesFromWriteFlag(e.write),r=await t.createPersonalAccessToken({name:e.name,scopes:n});if(!r.accessToken)throw Error(`Failed to create personal access token`);printCreatedToken(e.name,r.accessToken,e.write,`created`)}}),fa=N({name:`delete`,description:`Delete a personal access token.`,args:q.strictObject({name:W(q.string(),{positional:!0,description:`Token name`})}),run:async e=>{await R(),await(await createPatOperatorClient()).deletePersonalAccessToken({name:e.name}),c.success(`Personal access token "${e.name}" deleted successfully.`)}}),pa=N({name:`list`,description:`List all personal access tokens.`,args:q.strictObject({...Ye()}),run:async e=>{let t=c.jsonMode,n=await createPatOperatorClient(),r=f(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`
112
+ `)}async function createPatOperatorClient(e){let t=await h({profile:e});return await kn(t)}const ga=w({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:N.profile}),run:async e=>{await R({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 Error(`Failed to create personal access token`);printCreatedToken(e.name,r.accessToken,e.write,`created`)}}),_a=w({name:`delete`,description:`Delete a personal access token.`,args:q.strictObject({name:W(q.string(),{positional:!0,description:`Token name`}),profile:N.profile}),run:async e=>{await R({profile:e.profile}),await(await createPatOperatorClient(e.profile)).deletePersonalAccessToken({name:e.name}),c.success(`Personal access token "${e.name}" deleted successfully.`)}}),va=w({name:`list`,description:`List all personal access tokens.`,args:q.strictObject({...I(),profile:N.profile}),run:async e=>{let t=c.jsonMode,n=await createPatOperatorClient(e.profile),r=F(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`
114
113
  No personal access tokens found.
115
114
  Please create a token using 'tailor user pat create' command.
116
- `),!t))return;let a=i.map(transformPersonalAccessToken);if(t){c.out(a);return}let o=Math.max(...i.map(e=>e.name.length));i.forEach(e=>{let t=transformPersonalAccessToken(e),n=t.name.padStart(o);c.log(`${n}: ${t.scopes.join(`/`)}`)})}}),ma=N({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)`})}),run:async e=>{await R();let t=await createPatOperatorClient();await t.deletePersonalAccessToken({name:e.name});let n=getScopesFromWriteFlag(e.write),r=await t.createPersonalAccessToken({name:e.name,scopes:n});if(!r.accessToken)throw Error(`Failed to create personal access token`);printCreatedToken(e.name,r.accessToken,e.write,`updated`)}}),ha=G({name:`pat`,description:`Manage personal access tokens.`,subCommands:{list:pa,create:da,delete:fa,update:ma},async run(){await K(pa,[])}}),ga=N({name:`switch`,description:`Set current user.`,args:q.strictObject({user:W(q.string(),{positional:!0,description:`User email address or machine user client ID`})}),run:async e=>{let t=await D(),n=process.env.TAILOR_PLATFORM_PROFILE,r=n?t.profiles[n]:void 0;if(n&&!r)throw Error(`Profile "${n}" not found`);let i=r?j(r):void 0;if(e.user.includes(`|`))throw Error(`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.`);let a=pe(t,e.user,i);if(!a)throw Error(H`
115
+ `),!t))return;let a=i.map(transformPersonalAccessToken);c.out(a,{display:{scopes:e=>e.join(`/`),lastUsedAt:e=>e===null?`never`:At(e)}})}}),ya=w({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:N.profile}),run:async e=>{await R({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 Error(`Failed to create personal access token`);printCreatedToken(e.name,r.accessToken,e.write,`updated`)}}),ba=G({name:`pat`,description:`Manage personal access tokens.`,subCommands:{list:va,create:ga,delete:_a,update:ya},async run(){await K(va,[])}}),xa=w({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:N.profile}),run:async e=>{let t=await B(),n=e.profile||process.env.TAILOR_PLATFORM_PROFILE,r=n?t.profiles[n]:void 0;if(n&&!r)throw Error(`Profile "${n}" not found`);let i=r?Pe(r):void 0;if(e.user.includes(`|`))throw Error(`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.`);let a=Ve(t,e.user,i);if(!a)throw Error(H`
117
116
  User "${e.user}" not found.
118
117
  Please login first using 'tailor login' command to register this user.
119
- `);r?r.user=a:t.current_user=a,_(t),c.success(`Current user set to "${a}" successfully.`)}}),_a=G({name:`user`,description:`Manage Tailor Platform users.`,subCommands:{current:la,list:ua,switch:ga,pat:ha},async run(){await K(ua,[])}}),va=G({name:`workflow`,description:`Manage workflows and workflow executions.`,subCommands:{list:xe,get:Be,start:ae,wait:nn,executions:de,resume:ee},async run(){await K(xe,[])}}),ya=G({name:`app`,description:`Manage workspace applications`,subCommands:{health:v,list:sn},async run(){await K(sn,[])}}),ba=G({name:`user`,description:`Manage workspace users`,subCommands:{invite:dt,list:Xt,remove:ot,update:Pt},async run(){await K(Xt,[])}}),xa=G({name:`workspace`,description:`Manage Tailor Platform workspaces.`,subCommands:{app:ya,create:bt,delete:$t,get:mt,list:Mt,restore:At,user:ba},async run(){await K(Mt,[])}});await Kt(new URL(`./ts-hook.mjs`,import.meta.url)),ir();const Sa=await Gn(),Ca=Object.keys(Sa.bin??{})[0]||`tailor`,wa=Sa.name??`@tailor-platform/sdk`,Ta=await ur(import.meta.url),Ea=lr(cr(Ta),`agent-skills`);function defaultSkillsRunToAdd(e){let t=(e.subCommands??{}).add;return{...e,async run(){let e=await K(t,[]);if(!e.success)throw e.error}}}const Da=hr(G({name:Ca,description:Sa.description||`Tailor CLI for managing Tailor Platform SDK applications`,notes:`CLI plugins (beta): an unknown subcommand is dispatched to an external plugin executable named \`${Ca}-<name>\` (found on your PATH or in node_modules/.bin), similar to \`gh\` extensions.
120
- Run \`${Ca} plugin list\` to see which plugins are installed and where they resolve from.
121
- The \`setup\` commands are provided by the @tailor-platform/sdk-plugin-setup CLI plugin.`,subCommands:{api:Vr,auth:Ur,authconnection:Xr,crashreport:$r,deploy:ei,executor:ti,function:di,generate:fi,init:pi,login:gi,logout:_i,machineuser:vi,oauth2client:yi,open:bi,organization:Si,plugin:Di,profile:Mi,query:$e,remove:le,secret:Gi,show:Re,staticwebsite:Qi,tailordb:sa,upgrade:ca,user:_a,workflow:va,workspace:xa}}),{sourceDir:Ea,package:wa,mode:`copy`,descriptionAppend:!1,globalArgs:q.object(Ie),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.`}}),Oa=mr({...Da,subCommands:{...Da.subCommands,skills:defaultSkillsRunToAdd(Da.subCommands.skills)}});fr(Oa,{version:Sa.version,globalArgs:q.object(Ie),displayErrors:!1,onUnknownSubcommand:({commandPath:e,name:t,args:n})=>dispatchPluginWithInstallHint({commandPath:e,name:t,args:n,cliName:Ca,profile:process.env.TAILOR_PLATFORM_PROFILE}),cleanup:async({error:e})=>{if(e){if(c.jsonMode)c.log(Bt(e,{includeStack:c.verbose}));else if(Jn(e))c.log(e.format()),c.verbose&&e.stack&&c.debug(`\nStack trace:\n${e.stack}`);else if(e instanceof Error){c.error(e.message);let t=Xn(e);t&&c.log(` ${l.info(`Suggestion:`)} ${t}`),c.verbose&&e.stack&&c.debug(`\nStack trace:\n${e.stack}`)}else c.error(`Unknown error: ${e}`);if(!Jn(e)&&(!(e instanceof Error)||e instanceof TypeError||e instanceof RangeError)){let{reportCrash:t}=await import(`../crashreport-By23O2k-.mjs`);await t(e,`handledError`)}}let{shutdownTelemetry:t}=await import(`../telemetry-DXHP3VVi.mjs`);await t()}});export{Oa as mainCommand};
118
+ `);r?r.user=a:t.current_user=a,k(t),c.success(`Current user set to "${a}" successfully.`)}}),Sa=G({name:`user`,description:`Manage Tailor Platform users.`,subCommands:{current:ma,list:ha,switch:xa,pat:ba},async run(){await K(ha,[])}}),Ca=G({name:`workflow`,description:`Manage workflows and workflow executions.`,subCommands:{list:De,get:We,start:le,wait:sn,executions:ge,resume:te},async run(){await K(De,[])}}),wa=G({name:`app`,description:`Manage workspace applications`,subCommands:{health:v,list:un},async run(){await K(un,[])}}),Ta=G({name:`user`,description:`Manage workspace users`,subCommands:{invite:ht,list:nn,remove:st,update:zt},async run(){await K(nn,[])}}),Ea=G({name:`workspace`,description:`Manage Tailor Platform workspaces.`,subCommands:{app:wa,create:Ct,delete:rn,get:vt,list:Lt,restore:Nt,user:Ta},async run(){await K(Lt,[])}});await Qt(new URL(`./ts-hook.mjs`,import.meta.url)),cr();const Da=await Yn(),Oa=Object.keys(Da.bin??{})[0]||`tailor`,ka=Da.name??`@tailor-platform/sdk`,Aa=await mr(import.meta.url),ja=pr(fr(Aa),`agent-skills`);function defaultSkillsRunToAdd(e){let t=(e.subCommands??{}).add;return{...e,async run(){let e=await K(t,[]);if(!e.success)throw e.error}}}const Ma=yr(G({name:Oa,description:Da.description||`Tailor CLI for managing Tailor Platform SDK applications`,notes:`CLI plugins (beta): an unknown subcommand is dispatched to an external plugin executable named \`${Oa}-<name>\` (found on your PATH or in node_modules/.bin), similar to \`gh\` extensions.
119
+ Run \`${Oa} plugin list\` to see which plugins are installed and where they resolve from.
120
+ The \`setup\` commands are provided by the @tailor-platform/sdk-plugin-setup CLI plugin.`,subCommands:{api:Gr,auth:Jr,authconnection:ti,crashreport:ii,deploy:ai,executor:oi,function:gi,generate:_i,init:vi,login:xi,logout:Si,machineuser:Ci,oauth2client:wi,open:Ti,organization:Di,plugin:Mi,profile:Li,query:et,remove:he,secret:Xi,show:He,staticwebsite:ra,tailordb:fa,upgrade:pa,user:Sa,workflow:Ca,workspace:Ea}}),{sourceDir:ja,package:ka,mode:`copy`,descriptionAppend:!1,globalArgs:q.object(Gt),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.`}}),Na=vr({...Ma,subCommands:{...Ma.subCommands,skills:defaultSkillsRunToAdd(Ma.subCommands.skills)}});gr(Na,{version:Da.version,globalArgs:q.object(Gt),displayErrors:!1,onUnknownSubcommand:({commandPath:e,name:t,args:n})=>dispatchPluginWithInstallHint({commandPath:e,name:t,args:n,cliName:Oa,profile:process.env.TAILOR_PLATFORM_PROFILE}),cleanup:async({error:e})=>{if(e){if(c.jsonMode)c.log(Kt(e,{includeStack:c.verbose}));else if(Qn(e))c.log(e.format()),c.verbose&&e.stack&&c.debug(`\nStack trace:\n${e.stack}`);else if(e instanceof Error){c.error(e.message);let t=er(e);t&&c.log(` ${l.info(`Suggestion:`)} ${t}`),c.verbose&&e.stack&&c.debug(`\nStack trace:\n${e.stack}`)}else c.error(`Unknown error: ${e}`);if(!Qn(e)&&(!(e instanceof Error)||e instanceof TypeError||e instanceof RangeError)){let{reportCrash:t}=await import(`../crashreport-By23O2k-.mjs`);await t(e,`handledError`)}}let{shutdownTelemetry:t}=await import(`../telemetry-DXHP3VVi.mjs`);await t()}});export{Na as mainCommand};
122
121
  //# sourceMappingURL=main.mjs.map