@tailor-platform/sdk 2.18.0 → 2.19.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 (53) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/{application-DEkgf2w1.mjs → application-BYlhYQyh.mjs} +2 -2
  3. package/dist/{application-DEkgf2w1.mjs.map → application-BYlhYQyh.mjs.map} +1 -1
  4. package/dist/application-KZRJHv2j.mjs +1 -0
  5. package/dist/cli/commands/deploy/event-subscriptions.d.mts +1 -0
  6. package/dist/cli/commands/generate/service.d.mts +1 -0
  7. package/dist/cli/lib.mjs +1 -1
  8. package/dist/cli/main.mjs +3 -3
  9. package/dist/cli/services/executor/service.d.mts +1 -0
  10. package/dist/completion/zsh-worker.zsh +1 -1
  11. package/dist/configure/index.d.mts +7 -7
  12. package/dist/configure/index.mjs +1 -1
  13. package/dist/configure/index.mjs.map +1 -1
  14. package/dist/configure/types/field.types.d.mts +24 -4
  15. package/dist/configure/types/type.d.mts +1 -0
  16. package/dist/date-B7-oyTGE.mjs +2 -0
  17. package/dist/date-B7-oyTGE.mjs.map +1 -0
  18. package/dist/field-parse-BbNyotv5.mjs +2 -0
  19. package/dist/field-parse-BbNyotv5.mjs.map +1 -0
  20. package/dist/{manager-C26Gi1bX.mjs → manager-qfbUL7ru.mjs} +2 -2
  21. package/dist/{manager-C26Gi1bX.mjs.map → manager-qfbUL7ru.mjs.map} +1 -1
  22. package/dist/parser/service/auth/schema.d.mts +1 -0
  23. package/dist/plugin/index.mjs +1 -1
  24. package/dist/{register-ts-hook-BD3ArLqY.mjs → register-ts-hook-Djjnj5R8.mjs} +3 -3
  25. package/dist/{register-ts-hook-BD3ArLqY.mjs.map → register-ts-hook-Djjnj5R8.mjs.map} +1 -1
  26. package/dist/runtime/date.d.mts +3 -3
  27. package/dist/runtime/field-parse.d.mts +1 -0
  28. package/dist/runtime/index.d.mts +2 -1
  29. package/dist/runtime/index.mjs +1 -1
  30. package/dist/runtime/temporal.d.mts +31 -0
  31. package/dist/{schema-DRyQEabV.mjs → schema-BKvcWdVf.mjs} +2 -2
  32. package/dist/{schema-DRyQEabV.mjs.map → schema-BKvcWdVf.mjs.map} +1 -1
  33. package/dist/service-BgrEteZ2.mjs +1 -0
  34. package/dist/service-CuqkHP1r.mjs +7 -0
  35. package/dist/service-CuqkHP1r.mjs.map +1 -0
  36. package/dist/types/field.generated.d.mts +1 -1
  37. package/dist/types/helpers.d.mts +8 -6
  38. package/dist/utils/test/index.mjs +1 -1
  39. package/dist/vitest/environment.mjs +1 -1
  40. package/dist/vitest/environment.mjs.map +1 -1
  41. package/docs/github-actions.md +22 -15
  42. package/docs/migration/v3.md +0 -33
  43. package/docs/services/resolver.md +53 -1
  44. package/docs/testing.md +17 -0
  45. package/package.json +5 -3
  46. package/dist/application-Dl94fzpm.mjs +0 -1
  47. package/dist/date-CGBZbMW5.mjs +0 -2
  48. package/dist/date-CGBZbMW5.mjs.map +0 -1
  49. package/dist/field-parse-CzlKC4b7.mjs +0 -2
  50. package/dist/field-parse-CzlKC4b7.mjs.map +0 -1
  51. package/dist/service-B3OiWCYg.mjs +0 -1
  52. package/dist/service-eM7Fd8zS.mjs +0 -7
  53. package/dist/service-eM7Fd8zS.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./application-BYlhYQyh.mjs";export{t as defineApplication,e as generatePluginFilesIfNeeded};
@@ -1,3 +1,4 @@
1
+ import "../../../types/executor.generated.mjs";
1
2
  import "./label.mjs";
2
3
  import "./workflow.mjs";
3
4
  import "./deployment-target.mjs";
@@ -1,4 +1,5 @@
1
1
  import "../../../parser/service/tailordb/types.mjs";
2
+ import "../../../types/executor.generated.mjs";
2
3
  import "../../../plugin/types.mjs";
3
4
  import "../../../plugin/manager.mjs";
4
5
  import "../../shared/config-loader.mjs";
package/dist/cli/lib.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{i as ee,n as te}from"../logger-72hM4JWZ.mjs";import{$r as ne,A as e,At as t,Bt as n,C as r,Ct as i,Di as a,Dr as o,E as s,Ei as c,Er as l,Et as u,F as d,Fn as f,Ft as p,G as m,Gt as h,H as g,Hr as _,Ht as v,I as y,In as b,Ir as x,L as S,Ln as C,Lr as w,Mn as T,Mr as E,Mt as D,N as O,Nn as k,O as A,Oi as j,Or as M,Ot as N,P,Pn as F,Pt as I,Qt as L,Rn as R,Rt as z,Si as B,Sr as V,St as H,Tr as U,Ur as W,Vt as G,W as K,Wr as q,Wt as J,X as Y,Xn as X,Yt as Z,Z as re,Zr as ie,Zt as ae,_ as oe,_n as se,_r as Q,_t as ce,bt as le,cn as ue,ct as de,d as fe,ei as pe,et as me,fr as he,ft as ge,gr as _e,gt as ve,h as ye,hr as be,i as xe,it as Se,j as Ce,ji as we,ki as Te,kn as Ee,kt as De,l as Oe,ln as $,lr as ke,mn as Ae,mr as je,mt as Me,n as Ne,nr as Pe,nt as Fe,oi as Ie,ot as Le,p as Re,pi as ze,pr as Be,q as Ve,qt as He,r as Ue,s as We,t as Ge,ti as Ke,ut as qe,vr as Je,wr as Ye,x as Xe,xt as Ze,y as Qe,yr as $e,zi as et,zn as tt}from"../register-ts-hook-BD3ArLqY.mjs";import{et as nt}from"../application-DEkgf2w1.mjs";import{t as rt}from"../type-source--ZNcV8RJ.mjs";import{arg as it,defineCommand as at,runCommand as ot,runMain as st}from"@politty/zod";await Ge(new URL(`./ts-hook.mjs`,import.meta.url));export{Be as DB_PGLITE_SCHEMA_FILE_NAME,je as DB_TYPES_FILE_NAME,be as DIFF_FILE_NAME,_e as INITIAL_SCHEMA_NUMBER,Q as MIGRATE_FILE_NAME,Je as MIGRATE_PGLITE_TEST_FILE_NAME,$e as MIGRATE_TEST_FILE_NAME,E as MIGRATION_LABEL_KEY,V as SCHEMA_FILE_NAME,T as TAILOR_LOCK_FILENAME,k as TAILOR_LOCK_VERSION,Ne as annotateTerminalError,ne as apiCall,$ as apply,$ as deploy,it as arg,pe as assertWritable,X as bundleMigrationScript,d as bundleSeedDumpScript,y as bundleSeedScript,P as chunkSeedData,x as compareLocalTypesWithSnapshot,w as compareSnapshots,c as configArg,a as confirmationArgs,j as createCommonArgs,ge as createFolder,ke as createSnapshotFromLocalTypes,se as createWorkspace,B as defineAppCommand,at as defineCommand,qe as deleteFolder,Qe as deleteWorkspace,K as deployStaticWebsite,Te as deploymentArgs,R as ensureConfigId,H as errorToJson,De as executeScript,N as extractOwnedNamespaces,F as findAppIdLock,_ as formatDiffSummary,W as formatMigrationDiff,Ze as generate,tt as generateUserTypes,r as getAppHealth,ue as getExecutor,G as getExecutorJob,v as getExecutorWaitFailureMessage,de as getFolder,I as getFunctionRegistry,Ye as getLatestMigrationNumber,ce as getMachineUserToken,U as getMigrationDirPath,l as getMigrationFilePath,o as getMigrationFiles,Pe as getNamespacesWithMigrations,M as getNextMigrationNumber,ve as getOAuth2Client,Fe as getOrganization,Z as getWorkflow,ae as getWorkflowExecution,oe as getWorkspace,q as hasChanges,nt as initOperatorClient,Re as inviteUser,rt as isPluginGeneratedTable,Xe as listApps,J as listExecutorJobs,n as listExecutors,Le as listFolders,D as listFunctionRegistries,le as listMachineUsers,Me as listOAuth2Clients,me as listOrganizations,fe as listUsers,p as listWebhookExecutors,L as listWorkflowExecutions,e as listWorkflows,Ae as listWorkspaces,Ie as loadAccessToken,Ke as loadConfig,we as loadEnvFiles,O as loadSeedContext,u as loadTailorDBNamespaces,ze as loadWorkspaceId,g as logBetaWarning,te as logger,S as migrateGenerate,re as organizationTree,f as parseAppIds,b as planAppIds,ie as prompt,xe as query,he as reconstructSnapshotFromMigrations,Ve as remove,C as removeAdoptedConfigIds,Oe as removeUser,ye as restoreWorkspace,A as resumeWorkflow,ot as runCommand,st as runMain,i as serializeError,m as show,He as startWorkflow,ee as styles,z as triggerExecutor,Ce as truncate,Se as updateFolder,Y as updateOrganization,We as updateUser,t as waitForExecution,s as waitWorkflowExecution,h as watchExecutorJob,Ue as withSourceLocation,et as workspaceArgs,Ee as workspaceNameSchema};
1
+ import{i as ee,n as te}from"../logger-72hM4JWZ.mjs";import{$r as ne,A as e,At as t,Bt as n,C as r,Ct as i,Di as a,Dr as o,E as s,Ei as c,Er as l,Et as u,F as d,Fn as f,Ft as p,G as m,Gt as h,H as g,Hr as _,Ht as v,I as y,In as b,Ir as x,L as S,Ln as C,Lr as w,Mn as T,Mr as E,Mt as D,N as O,Nn as k,O as A,Oi as j,Or as M,Ot as N,P,Pn as F,Pt as I,Qt as L,Rn as R,Rt as z,Si as B,Sr as V,St as H,Tr as U,Ur as W,Vt as G,W as K,Wr as q,Wt as J,X as Y,Xn as X,Yt as Z,Z as re,Zr as ie,Zt as ae,_ as oe,_n as se,_r as Q,_t as ce,bt as le,cn as ue,ct as de,d as fe,ei as pe,et as me,fr as he,ft as ge,gr as _e,gt as ve,h as ye,hr as be,i as xe,it as Se,j as Ce,ji as we,ki as Te,kn as Ee,kt as De,l as Oe,ln as $,lr as ke,mn as Ae,mr as je,mt as Me,n as Ne,nr as Pe,nt as Fe,oi as Ie,ot as Le,p as Re,pi as ze,pr as Be,q as Ve,qt as He,r as Ue,s as We,t as Ge,ti as Ke,ut as qe,vr as Je,wr as Ye,x as Xe,xt as Ze,y as Qe,yr as $e,zi as et,zn as tt}from"../register-ts-hook-Djjnj5R8.mjs";import{et as nt}from"../application-BYlhYQyh.mjs";import{t as rt}from"../type-source--ZNcV8RJ.mjs";import{arg as it,defineCommand as at,runCommand as ot,runMain as st}from"@politty/zod";await Ge(new URL(`./ts-hook.mjs`,import.meta.url));export{Be as DB_PGLITE_SCHEMA_FILE_NAME,je as DB_TYPES_FILE_NAME,be as DIFF_FILE_NAME,_e as INITIAL_SCHEMA_NUMBER,Q as MIGRATE_FILE_NAME,Je as MIGRATE_PGLITE_TEST_FILE_NAME,$e as MIGRATE_TEST_FILE_NAME,E as MIGRATION_LABEL_KEY,V as SCHEMA_FILE_NAME,T as TAILOR_LOCK_FILENAME,k as TAILOR_LOCK_VERSION,Ne as annotateTerminalError,ne as apiCall,$ as apply,$ as deploy,it as arg,pe as assertWritable,X as bundleMigrationScript,d as bundleSeedDumpScript,y as bundleSeedScript,P as chunkSeedData,x as compareLocalTypesWithSnapshot,w as compareSnapshots,c as configArg,a as confirmationArgs,j as createCommonArgs,ge as createFolder,ke as createSnapshotFromLocalTypes,se as createWorkspace,B as defineAppCommand,at as defineCommand,qe as deleteFolder,Qe as deleteWorkspace,K as deployStaticWebsite,Te as deploymentArgs,R as ensureConfigId,H as errorToJson,De as executeScript,N as extractOwnedNamespaces,F as findAppIdLock,_ as formatDiffSummary,W as formatMigrationDiff,Ze as generate,tt as generateUserTypes,r as getAppHealth,ue as getExecutor,G as getExecutorJob,v as getExecutorWaitFailureMessage,de as getFolder,I as getFunctionRegistry,Ye as getLatestMigrationNumber,ce as getMachineUserToken,U as getMigrationDirPath,l as getMigrationFilePath,o as getMigrationFiles,Pe as getNamespacesWithMigrations,M as getNextMigrationNumber,ve as getOAuth2Client,Fe as getOrganization,Z as getWorkflow,ae as getWorkflowExecution,oe as getWorkspace,q as hasChanges,nt as initOperatorClient,Re as inviteUser,rt as isPluginGeneratedTable,Xe as listApps,J as listExecutorJobs,n as listExecutors,Le as listFolders,D as listFunctionRegistries,le as listMachineUsers,Me as listOAuth2Clients,me as listOrganizations,fe as listUsers,p as listWebhookExecutors,L as listWorkflowExecutions,e as listWorkflows,Ae as listWorkspaces,Ie as loadAccessToken,Ke as loadConfig,we as loadEnvFiles,O as loadSeedContext,u as loadTailorDBNamespaces,ze as loadWorkspaceId,g as logBetaWarning,te as logger,S as migrateGenerate,re as organizationTree,f as parseAppIds,b as planAppIds,ie as prompt,xe as query,he as reconstructSnapshotFromMigrations,Ve as remove,C as removeAdoptedConfigIds,Oe as removeUser,ye as restoreWorkspace,A as resumeWorkflow,ot as runCommand,st as runMain,i as serializeError,m as show,He as startWorkflow,ee as styles,z as triggerExecutor,Ce as truncate,Se as updateFolder,Y as updateOrganization,We as updateUser,t as waitForExecution,s as waitWorkflowExecution,h as watchExecutorJob,Ue as withSourceLocation,et as workspaceArgs,Ee as workspaceNameSchema};
2
2
  //# sourceMappingURL=lib.mjs.map
package/dist/cli/main.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{n as e}from"../field-parse-CzlKC4b7.mjs";import{E as t,It as n,Ut as r,kt as i,q as a}from"../workspace_resource_pb-BOoRts_z.mjs";import{t as o}from"../assert-WeXvmG4j.mjs";import{i as s,n as c,o as l}from"../logger-72hM4JWZ.mjs";import{$ as u,$n as d,$r as f,$t as p,Ai as m,An as h,Ar as g,B as _,Bn as v,Br as y,Ci as b,Cn as x,Cr as ee,Ct as S,D as te,Di as C,Dn as w,Dr as ne,Dt as re,Ei as ie,En as ae,Er as oe,Et as se,Fi as ce,Fr as le,Gn as ue,Gr as de,H as fe,Hn as pe,Hr as me,I as he,Ii as T,Ir as ge,It as _e,J as ve,Jn as ye,Jr as be,Jt as xe,K as Se,Kn as Ce,Kr as E,Kt as we,Li as Te,Lr as Ee,Lt as De,M as Oe,Mi as ke,Mr as Ae,N as je,Ni as Me,Nr as Ne,Nt as Pe,On as Fe,Ot as Ie,P as Le,Pi as Re,Pr as ze,Q as Be,Qn as Ve,Qr as D,R as He,Ri as Ue,S as We,Si as O,Sn as Ge,T as Ke,Ti as qe,Tn as Je,Tt as Ye,U as Xe,Un as Ze,Ur as Qe,Ut as $e,V as et,Vn as tt,Vr as nt,Wn as rt,Wr as it,Xn as at,Xr as ot,Xt as st,Y as ct,Yn as lt,Yr as ut,Zn as dt,Zr as k,_i as ft,a as pt,ai as mt,an as ht,ar as gt,at as _t,b as vt,bi as yt,bn as bt,br as xt,c as St,ci as Ct,cr as wt,di as Tt,dn as Et,dr as Dt,dt as Ot,ei as A,en as kt,er as At,f as jt,fi as Mt,fn as Nt,fr as j,g as Pt,gi as Ft,gn as It,hi as M,hn as Lt,ht as Rt,ii as zt,in as Bt,ir as Vt,jn as Ht,jr as Ut,jt as Wt,k as Gt,ki as N,kr as Kt,kt as qt,li as Jt,lr as Yt,lt as Xt,m as Zt,mi as P,n as Qt,ni as $t,nn as en,nr as F,o as tn,oi as nn,on as rn,or as an,pi as on,pn as sn,pt as cn,qn as ln,qr as un,ri as dn,rn as fn,rr as pn,rt as mn,si as hn,sn as gn,sr as _n,st as vn,t as yn,ti as I,tn as bn,tr as xn,tt as Sn,u as Cn,ui as wn,un as Tn,ur as En,v as Dn,vi as On,vn as kn,vt as An,w as jn,wn as Mn,wr as Nn,wt as Pn,xi as L,xn as Fn,xr as In,xt as Ln,yi as Rn,yn as zn,yt as Bn,z as Vn,zi as R,zr as z,zt as Hn}from"../register-ts-hook-BD3ArLqY.mjs";import{$ as Un,A as Wn,F as Gn,H as Kn,I as qn,J as Jn,K as B,L as Yn,M as Xn,N as Zn,P as Qn,Q as $n,U as er,V as tr,W as nr,X as rr,Z as ir,_ as ar,b as or,d as sr,et as cr,h as lr,j as ur,lt as dr,m as fr,o as pr,ot as mr,q as hr,s as gr,tt as _r,x as vr}from"../application-DEkgf2w1.mjs";import{g as yr,i as br,r as xr}from"../service-eM7Fd8zS.mjs";import{t as V}from"../multiline-EyzjEwn9.mjs";import{t as Sr}from"../package-json-C690ceex.mjs";import{t as Cr}from"../user-agent-vdHYF3QL.mjs";import{a as H,c as wr,i as Tr,n as Er,o as Dr,r as Or,s as kr,t as U}from"../errors-BjJnpXkK.mjs";import{t as Ar}from"../service_pb-DprmLNsq.mjs";import{a as jr,i as Mr,o as Nr,r as Pr,t as Fr}from"../crashreport-Cyuz1qiu.mjs";import{t as Ir}from"../manager-C26Gi1bX.mjs";import{a as Lr,i as Rr,n as zr}from"../kysely-type-B_oA8D1k.mjs";import{arg as W,defineCommand as G,extractFields as Br,runMain as Vr,toCamelCase as Hr}from"@politty/zod";import{withCompletionCommand as Ur}from"@politty/zod/completion";import{withSkillCommand as Wr}from"@politty/zod/skill";import*as K from"pathe";import{dirname as Gr,resolve as Kr}from"pathe";import{resolvePackageJSON as qr}from"pkg-types";import{z as q}from"zod";import{ScalarType as J,create as Jr}from"@bufbuild/protobuf";import*as Y from"node:fs";import{accessSync as Yr,constants as Xr,readdirSync as Zr}from"node:fs";import{timestampDate as X}from"@bufbuild/protobuf/wkt";import{pathToFileURL as Qr}from"node:url";import{generateCodeVerifier as $r}from"@badgateway/oauth2-client";import{Code as Z,ConnectError as Q}from"@connectrpc/connect";import*as ei from"node:crypto";import{randomBytes as ti}from"node:crypto";import*as ni from"node:http";import ri from"open";import*as ii from"rolldown";import{parseSync as ai}from"oxc-parser";import*as oi from"node:os";import*as $ from"node:fs/promises";import{setTimeout as si}from"node:timers/promises";import{TraceMap as ci,generatedPositionFor as li,originalPositionFor as ui}from"@jridgewell/trace-mapping";import{spawn as di,spawnSync as fi}from"node:child_process";const pi=Ar.methods.filter(e=>e.methodKind===`unary`);function listMethodNames(){return pi.map(e=>e.name).toSorted()}function listMethodChoices(){return pi.flatMap(e=>[e.name,`${Ar.typeName}/${e.name}`]).toSorted()}function getMethodDescriptor(e){return pi.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 mi=new Set([`google.protobuf.Struct`,`google.protobuf.Value`,`google.protobuf.ListValue`,`google.protobuf.NullValue`,`google.protobuf.Any`,`google.protobuf.Empty`]);function isUnrepresentableWellKnownType(e){return mi.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 hi={[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 hi[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(`
2
+ import{n as e}from"../field-parse-BbNyotv5.mjs";import{E as t,It as n,Ut as r,kt as i,q as a}from"../workspace_resource_pb-BOoRts_z.mjs";import{t as o}from"../assert-WeXvmG4j.mjs";import{i as s,n as c,o as l}from"../logger-72hM4JWZ.mjs";import{$ as u,$n as d,$r as f,$t as p,Ai as m,An as h,Ar as g,B as _,Bn as v,Br as y,Ci as b,Cn as x,Cr as ee,Ct as S,D as te,Di as C,Dn as w,Dr as ne,Dt as re,Ei as ie,En as ae,Er as oe,Et as se,Fi as ce,Fr as le,Gn as ue,Gr as de,H as fe,Hn as pe,Hr as me,I as he,Ii as T,Ir as ge,It as _e,J as ve,Jn as ye,Jr as be,Jt as xe,K as Se,Kn as Ce,Kr as E,Kt as we,Li as Te,Lr as Ee,Lt as De,M as Oe,Mi as ke,Mr as Ae,N as je,Ni as Me,Nr as Ne,Nt as Pe,On as Fe,Ot as Ie,P as Le,Pi as Re,Pr as ze,Q as Be,Qn as Ve,Qr as D,R as He,Ri as Ue,S as We,Si as O,Sn as Ge,T as Ke,Ti as qe,Tn as Je,Tt as Ye,U as Xe,Un as Ze,Ur as Qe,Ut as $e,V as et,Vn as tt,Vr as nt,Wn as rt,Wr as it,Xn as at,Xr as ot,Xt as st,Y as ct,Yn as lt,Yr as ut,Zn as dt,Zr as k,_i as ft,a as pt,ai as mt,an as ht,ar as gt,at as _t,b as vt,bi as yt,bn as bt,br as xt,c as St,ci as Ct,cr as wt,di as Tt,dn as Et,dr as Dt,dt as Ot,ei as A,en as kt,er as At,f as jt,fi as Mt,fn as Nt,fr as j,g as Pt,gi as Ft,gn as It,hi as M,hn as Lt,ht as Rt,ii as zt,in as Bt,ir as Vt,jn as Ht,jr as Ut,jt as Wt,k as Gt,ki as N,kr as Kt,kt as qt,li as Jt,lr as Yt,lt as Xt,m as Zt,mi as P,n as Qt,ni as $t,nn as en,nr as F,o as tn,oi as nn,on as rn,or as an,pi as on,pn as sn,pt as cn,qn as ln,qr as un,ri as dn,rn as fn,rr as pn,rt as mn,si as hn,sn as gn,sr as _n,st as vn,t as yn,ti as I,tn as bn,tr as xn,tt as Sn,u as Cn,ui as wn,un as Tn,ur as En,v as Dn,vi as On,vn as kn,vt as An,w as jn,wn as Mn,wr as Nn,wt as Pn,xi as L,xn as Fn,xr as In,xt as Ln,yi as Rn,yn as zn,yt as Bn,z as Vn,zi as R,zr as z,zt as Hn}from"../register-ts-hook-Djjnj5R8.mjs";import{$ as Un,A as Wn,F as Gn,H as Kn,I as qn,J as Jn,K as B,L as Yn,M as Xn,N as Zn,P as Qn,Q as $n,U as er,V as tr,W as nr,X as rr,Z as ir,_ as ar,b as or,d as sr,et as cr,h as lr,j as ur,lt as dr,m as fr,o as pr,ot as mr,q as hr,s as gr,tt as _r,x as vr}from"../application-BYlhYQyh.mjs";import{g as yr,i as br,r as xr}from"../service-CuqkHP1r.mjs";import{t as V}from"../multiline-EyzjEwn9.mjs";import{t as Sr}from"../package-json-C690ceex.mjs";import{t as Cr}from"../user-agent-vdHYF3QL.mjs";import{a as H,c as wr,i as Tr,n as Er,o as Dr,r as Or,s as kr,t as U}from"../errors-BjJnpXkK.mjs";import{t as Ar}from"../service_pb-DprmLNsq.mjs";import{a as jr,i as Mr,o as Nr,r as Pr,t as Fr}from"../crashreport-Cyuz1qiu.mjs";import{t as Ir}from"../manager-qfbUL7ru.mjs";import{a as Lr,i as Rr,n as zr}from"../kysely-type-B_oA8D1k.mjs";import{arg as W,defineCommand as G,extractFields as Br,runMain as Vr,toCamelCase as Hr}from"@politty/zod";import{withCompletionCommand as Ur}from"@politty/zod/completion";import{withSkillCommand as Wr}from"@politty/zod/skill";import*as K from"pathe";import{dirname as Gr,resolve as Kr}from"pathe";import{resolvePackageJSON as qr}from"pkg-types";import{z as q}from"zod";import{ScalarType as J,create as Jr}from"@bufbuild/protobuf";import*as Y from"node:fs";import{accessSync as Yr,constants as Xr,readdirSync as Zr}from"node:fs";import{timestampDate as X}from"@bufbuild/protobuf/wkt";import{pathToFileURL as Qr}from"node:url";import{generateCodeVerifier as $r}from"@badgateway/oauth2-client";import{Code as Z,ConnectError as Q}from"@connectrpc/connect";import*as ei from"node:crypto";import{randomBytes as ti}from"node:crypto";import*as ni from"node:http";import ri from"open";import*as ii from"rolldown";import{parseSync as ai}from"oxc-parser";import*as oi from"node:os";import*as $ from"node:fs/promises";import{setTimeout as si}from"node:timers/promises";import{TraceMap as ci,generatedPositionFor as li,originalPositionFor as ui}from"@jridgewell/trace-mapping";import{spawn as di,spawnSync as fi}from"node:child_process";const pi=Ar.methods.filter(e=>e.methodKind===`unary`);function listMethodNames(){return pi.map(e=>e.name).toSorted()}function listMethodChoices(){return pi.flatMap(e=>[e.name,`${Ar.typeName}/${e.name}`]).toSorted()}function getMethodDescriptor(e){return pi.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 mi=new Set([`google.protobuf.Struct`,`google.protobuf.Value`,`google.protobuf.ListValue`,`google.protobuf.NullValue`,`google.protobuf.Any`,`google.protobuf.Empty`]);function isUnrepresentableWellKnownType(e){return mi.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 hi={[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 hi[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
3
  `)}const gi=O({name:`inspect`,description:`Print the input message tree of an OperatorService endpoint.`,notes:"Combine with the global `--json` flag for a machine-readable descriptor. Recursive type references and `oneof` membership are annotated. Use `tailor api list` to discover endpoint names.",examples:[{cmd:`GetApplication`,desc:`Show fields of GetApplicationRequest.`},{cmd:`CreateExecutorExecutor`,desc:"Inspect a deeply nested input with `(oneof config)` annotations."}],args:q.strictObject({endpoint:W(q.string(),{positional:!0,description:`API endpoint to inspect (e.g., 'GetApplication' or 'tailor.v1.OperatorService/GetApplication').`,completion:{custom:{choices:listMethodNames()}}})}),run:e=>{let t=extractMethodName(e.endpoint),n=getMethodDescriptor(t);if(!n)throw U({code:`API_METHOD_UNKNOWN`,message:`unknown method: ${t}`,suggestion:"Run `tailor api list` to see available methods.",command:`api inspect`});c.jsonMode?c.out(renderInspectJson(n)):c.out(renderInspectText(n))}}),_i=O({name:`list`,description:`List all invocable OperatorService methods.`,notes:`Only single-request (non-streaming) methods are listed, because the CLI issues a single JSON request and reads one JSON response.`,args:q.strictObject({}),run:()=>{let e=listMethodNames();if(c.jsonMode)c.out(e);else for(let t of e)c.out(t)}});function resolveNamespaceName(e,t){if(/Auth|Tenant|UserProfile/.test(e))return t.auth?.name;if(/IdP/.test(e))return t.idp?.length===1?o(t.idp[0],`idp config missing`).name:void 0;if(/TailorDB/.test(e)){let e=Object.keys(t.db??{});return e.length===1?e[0]:void 0}if(/Pipeline/.test(e)){let e=Object.keys(t.resolver??{});return e.length===1?e[0]:void 0}}function parseBodyAsObject(e){let t;try{t=JSON.parse(e)}catch{return}if(typeof t==`object`&&t&&!Array.isArray(t))return t}function setNestedPath(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){let n=o(t[e],`path segment missing`),i=r[n];(typeof i!=`object`||!i||Array.isArray(i))&&(r[n]={}),r=r[n]}r[o(t[t.length-1],`path last segment missing`)]=n}function coerceFieldValue(e,t){if(e&&e.fieldKind===`scalar`&&e.scalar===J.BOOL){if(t===`true`)return!0;if(t===`false`)return!1;throw U({code:`API_FIELD_VALUE_INVALID`,message:`Invalid value for bool field: '${t}'. Expected 'true' or 'false'.`,command:`api`})}return t}function normalizeBodyFieldKeys(e,t){let n=new Map;for(let e of t)n.set(e.name,e.localName),n.set(e.jsonName,e.localName);let r=!1;for(let t of Object.keys(e)){let i=n.get(t);i&&i!==t&&(Object.hasOwn(e,i)||(e[i]=e[t]),delete e[t],r=!0)}return r}const vi=new Set([`__proto__`,`constructor`,`prototype`]),yi=q.string().transform((e,t)=>{let n=e.indexOf(`=`);if(n<0)return t.addIssue({code:`custom`,message:`Invalid field format: '${e}'. Expected format: 'key=value' or 'a.b.c=value'`}),q.NEVER;let r=e.slice(0,n);if(r.length===0)return t.addIssue({code:`custom`,message:`Field key cannot be empty`}),q.NEVER;let i=r.split(`.`);if(i.some(e=>e.length===0))return t.addIssue({code:`custom`,message:`Invalid field key: '${r}'. Dotted segments cannot be empty`}),q.NEVER;let a=i.find(e=>vi.has(e));return a?(t.addIssue({code:`custom`,message:`Invalid field key: '${r}'. Segment '${a}' is not allowed.`}),q.NEVER):{path:i,value:e.slice(n+1)}}),bi=O({name:`api`,description:`Call Tailor Platform API endpoints directly.`,notes:"Use `tailor api list` to enumerate invocable methods and `tailor api inspect <endpoint>` to print an endpoint's input message tree (combine with `--json` for machine-readable output).\n\nThe request body is inferred from the target endpoint's request schema, and commonly required fields are auto-injected so they can be omitted from `--body`:\n\n- `workspaceId` — resolved from `-w` / `TAILOR_PLATFORM_WORKSPACE_ID` / the selected profile.\n- `namespaceName` — resolved from `tailor.config.ts` based on the endpoint's service:\n - Auth / Tenant / UserProfile endpoints use `auth.name`.\n - IdP / TailorDB / Pipeline endpoints use the sole configured namespace when exactly one is defined.\n\nValues already present in `--body` are never overridden. If a value cannot be resolved (e.g. no config found), injection is silently skipped and the server-side validation error takes precedence.\n\nUse `--field key=value` (repeatable) to set request body fields without writing JSON. Dotted keys (e.g. `application.name=foo`) build nested objects. `--field` overrides matching fields in `--body` and tab-completes from the endpoint's request schema.",examples:[{cmd:`GetApplication -b '{"applicationName":"app-1"}'`,desc:`Call an endpoint; workspaceId is auto-injected.`},{cmd:`GetApplication -f applicationName=app-1`,desc:`Same as above, using --field instead of --body.`},{cmd:`list`,desc:`List all invocable OperatorService methods.`},{cmd:`inspect GetApplication`,desc:`Show the input message tree for an endpoint.`}],subCommands:{list:_i,inspect:gi},args:q.strictObject({...R,...ie,body:W(q.string().default(`{}`),{alias:`b`,description:`Request body as JSON.`}),field:W(yi.array().optional(),{alias:`f`,description:"Set a body field as `key=value` (repeatable; dotted keys nest). Overrides --body.",completion:{custom:{expand:{dependsOn:[`endpoint`],enumerate:({endpoint:e})=>enumerateAllFieldCompletions(extractMethodName(e??``))}}}}),endpoint:W(q.string(),{positional:!0,description:`API endpoint to call (e.g., 'GetApplication' or 'tailor.v1.OperatorService/GetApplication').`,completion:{custom:{choices:listMethodChoices()}}})}),run:async e=>{await A({profile:e.profile});let t=extractMethodName(e.endpoint),n=getMethodDescriptor(t),r=parseBodyAsObject(e.body),i=!1;if(e.field&&e.field.length>0){if(!r)throw U({code:`API_OPTIONS_INVALID`,message:`--field requires --body to be a JSON object (or omitted).`,command:`api`});for(let t of e.field){let e=n?resolveLeafField(n.input,t.path):void 0;setNestedPath(r,t.path,coerceFieldValue(e,t.value))}i=!0}if(r&&n){normalizeBodyFieldKeys(r,n.input.fields)&&(i=!0);let a=n.input.fields.map(e=>e.localName);if(a.includes(`workspaceId`)&&!Object.hasOwn(r,`workspaceId`))try{r.workspaceId=await on({workspaceId:e[`workspace-id`],profile:e.profile}),i=!0}catch{}if(a.includes(`namespaceName`)&&!Object.hasOwn(r,`namespaceName`))try{let{config:n}=await I(e.config),a=resolveNamespaceName(t,n);a&&(r.namespaceName=a,i=!0)}catch{}}let a=await f({profile:e.profile,endpoint:e.endpoint,body:i&&r?JSON.stringify(r):e.body});c.out(JSON.stringify(a.data,null,2))}}),xi=O({name:`status`,description:`Show the active Tailor Platform authentication status without printing tokens.`,args:q.strictObject({profile:R.profile}),run:async({profile:e})=>{let t=await hn({profile:e});if(c.out(t),!t.authenticated)throw U({code:`NOT_AUTHENTICATED`,message:`Not authenticated.`,suggestion:`Log in and try again.`,next:{command:`tailor`,args:[`login`,...T({profile:e})]}})}}),Si=O({name:`token`,description:`Print a valid Tailor Platform access token to stdout, refreshing it first if expired.`,args:q.strictObject({profile:R.profile}),run:async({profile:e})=>{let t=await nn({profile:e});c.out(t)}}),Ci=G({name:`auth`,description:`Authentication helpers for scripts and plugins.`,subCommands:{status:xi,token:Si}}),wi={name:W(q.string(),{alias:`n`,description:`Auth connection name`})};async function fetchOIDCDiscovery(e){let t=e.replace(/\/$/,``)+`/.well-known/openid-configuration`,n=await fetch(t).catch(e=>{throw U({code:`OIDC_DISCOVERY_FAILED`,message:`Failed to fetch OIDC discovery from ${t}: ${kr(e).message}`,cause:e})});if(!n.ok)throw U({code:`OIDC_DISCOVERY_FAILED`,message:`Failed to fetch OIDC discovery from ${t}: ${n.status}`});return n.json()}function randomState$1(){return ei.randomBytes(32).toString(`base64url`)}const Ti=O({name:`authorize`,description:`Authorize an auth connection via OAuth2 flow.`,args:q.strictObject({...R,...wi,scopes:q.string().optional().default(`openid,profile,email`).describe(`OAuth2 scopes to request (comma-separated)`),port:q.coerce.number().optional().default(8080).describe(`Local callback server port`),"no-browser":q.boolean().optional().default(!1).describe(`Don't open browser automatically`)}),run:async e=>{await A({profile:e.profile});let t=Or([`tailor`,`authconnection`,`open`,...T({profile:e.profile,workspaceId:e[`workspace-id`]})]),{client:n,workspaceId:r}=await D({profile:e.profile,workspaceId:e[`workspace-id`]}),i=(await er(async(e,t)=>{let{connections:i,nextPageToken:a}=await n.listAuthConnections({workspaceId:r,pageToken:e,pageSize:t});return[i,a]})).find(t=>t.name===e.name);if(!i)throw U({code:`AUTH_CONNECTION_NOT_FOUND`,message:`Auth connection "${e.name}" not found.`});if(i.config.case!==`oauth2`)throw U({code:`AUTH_CONNECTION_NOT_OAUTH2`,message:`Auth connection "${e.name}" is not an OAuth2 connection.`});let a=i.config.value,o=`http://localhost:${e.port}/callback`,s=randomState$1(),l;l=a.authUrl?a.authUrl:(await fetchOIDCDiscovery(a.providerUrl)).authorization_endpoint;let u=new URL(l);u.searchParams.set(`client_id`,a.clientId),u.searchParams.set(`redirect_uri`,o),u.searchParams.set(`response_type`,`code`),u.searchParams.set(`scope`,e.scopes.replace(/,/g,` `)),u.searchParams.set(`state`,s),u.searchParams.set(`access_type`,`offline`),await new Promise((i,a)=>{let handleCallback=async(t,u)=>{if(!t.url?.startsWith(`/callback`)){u.writeHead(404),u.end(`Not found`);return}try{let a=new URL(t.url,`http://localhost:${e.port}`),d=a.searchParams.get(`code`),f=a.searchParams.get(`state`),p=a.searchParams.get(`error`);if(p)throw U({code:`AUTHORIZATION_FAILED`,message:`Authorization failed: ${p}`});if(f!==s)throw U({code:`AUTHORIZATION_STATE_MISMATCH`,message:`State mismatch — possible CSRF attack.`});if(!d)throw U({code:`AUTHORIZATION_CODE_MISSING`,message:`No authorization code received.`});c.registerSecret(d),await n.exchangeAuthConnectionAuthorizationCode({workspaceId:r,connectionName:e.name,authorizationCode:d,redirectUri:o}),u.writeHead(200,{"Content-Type":`text/html`}),u.end(`<html><body><h1>Authorization successful</h1><p>You can close this window.</p></body></html>`),l.close(),i()}catch(e){u.writeHead(400,{"Content-Type":`text/plain`}),u.end(`Authorization failed: ${e instanceof Error?e.message:`Unknown error`}`),l.close(),a(kr(e))}},l=ni.createServer((e,t)=>void handleCallback(e,t)),d=setTimeout(()=>{l.close(),a(U({code:`AUTHORIZATION_TIMEOUT`,message:`Authorization timeout exceeded (5 minutes).`}))},3e5);l.on(`close`,()=>{clearTimeout(d)}),l.on(`error`,n=>{clearTimeout(d);let r=n.code,i=r===`EADDRINUSE`||r===`EACCES`?`Try a different port with --port, or authorize via the Console instead:`:`Authorize via the Console instead:`;c.warn(`Could not start the local callback server on port ${e.port}${r?` (${r})`:``}.\n${i}\n ${t}`),a(n)});let announceAuthorizeUrl=async()=>{let n=u.toString();if(c.info(e[`no-browser`]?`Open this URL in your browser to authorize:\n\n${n}\n`:`Opening browser for authorization:\n\n${n}\n`),c.info(`If this flow doesn't complete, you can authorize via the Console instead:\n ${t}`),!e[`no-browser`])try{await ri(n)}catch{c.warn(`Failed to open browser automatically. Please open the URL above manually.`)}};l.listen(e.port,()=>void announceAuthorizeUrl())}),c.success(`Auth connection "${e.name}" authorized successfully.`)}}),Ei=O({name:`delete`,description:`Delete an auth connection entirely.`,args:q.strictObject({...R,...wi,...C}),run:async e=>{await A({profile:e.profile});let{client:t,workspaceId:n}=await D({profile:e.profile,workspaceId:e[`workspace-id`]});if(!e.yes&&await k.text({message:`Enter the connection name to confirm deletion ("${e.name}"):`})!==e.name){c.info(`Auth connection deletion cancelled.`);return}try{await t.deleteAuthConnection({workspaceId:n,connectionName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`AUTH_CONNECTION_NOT_FOUND`,message:`Auth connection "${e.name}" not found.`,cause:t}):t}c.success(`Auth connection "${e.name}" deleted.`)}});function connectionInfo(e){let t=e.config.case===`oauth2`?e.config.value:void 0;return{name:e.name,type:e.config.case??`unknown`,providerUrl:t?.providerUrl??``,issuerUrl:t?.issuerUrl??``,clientId:t?.clientId??``,authUrl:t?.authUrl??``,tokenUrl:t?.tokenUrl??``,createdAt:e.createdAt?X(e.createdAt):null}}const Di=O({name:`list`,description:`List all auth connections.`,args:q.strictObject({...R,...Re()}),run:async e=>{let{client:t,workspaceId:n}=await D({profile:e.profile,workspaceId:e[`workspace-id`]});try{let r=Ue(e.order),i=await B(async(e,i)=>{let{connections:a,nextPageToken:o}=await t.listAuthConnections({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e.limit});c.out(i.map(connectionInfo))}catch(e){if(e instanceof Q&&e.code===Z.NotFound){c.out([]);return}throw e}}}),Oi=O({name:`open`,description:`Open the auth connections page in the Tailor Platform Console.`,args:q.strictObject({...R}),run:async e=>{let t=await on({workspaceId:e[`workspace-id`],profile:e.profile}),n=l(process.env.TAILOR_CONSOLE_NEXT)===!0?`/workspaces/${t}/services/auth-connections`:`/workspaces/${t}/settings/connections`,r=await Jt({profile:e.profile,...e[`workspace-id`]===void 0?{}:{allowMissingProfile:!0}}),i=new URL(n,r).toString(),a=c.jsonMode;c.info(`Opening auth connections page in Tailor Platform Console...`);let o=!0;try{await ri(i)}catch{o=!1}if(a){c.out({consoleUrl:i,workspaceId:t,opened:o});return}o?(c.out(`Console URL: ${i}`),c.out(`Workspace ID: ${t}`)):c.warn(`Failed to open browser automatically. Please open this URL manually:\n${i}`)}}),ki=O({name:`revoke`,description:`Revoke an auth connection's tokens (keeps the connection; use 'delete' to remove it).`,notes:"Revoke invalidates the connection's active session and tokens but keeps the connection and its stored credentials, so it can be re-authorized later. Use `delete` to remove the connection entirely.",args:q.strictObject({...R,...wi,...C}),run:async e=>{await A({profile:e.profile});let{client:t,workspaceId:n}=await D({profile:e.profile,workspaceId:e[`workspace-id`]});if(!e.yes&&await k.text({message:`Enter the connection name to confirm revocation ("${e.name}"):`})!==e.name){c.info(`Auth connection revocation cancelled.`);return}try{await t.revokeAuthConnection({workspaceId:n,connectionName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`AUTH_CONNECTION_NOT_FOUND`,message:`Auth connection "${e.name}" not found.`,cause:t}):t}c.success(`Auth connection "${e.name}" revoked.`)}}),Ai=G({name:`authconnection`,description:`Manage auth connections.`,subCommands:{authorize:Ti,list:Di,open:Oi,revoke:ki,delete:Ei},async run(){await b(Di)}});function orderAndLimitCrashReports(e,t){let n=e.filter(e=>e.endsWith(Mr)).toSorted(),r=t.order===`asc`?n:n.toReversed();return t.limit&&t.limit>0?r.slice(0,t.limit):r}function formatCrashReportFiles(e,t){return e.map(e=>({file:e,path:K.join(t,e)}))}const ji=O({name:`list`,description:`List local crash report files.`,args:q.strictObject({...Re()}),run:async e=>{let t=Nr(),n=c.jsonMode;if(!t.localDir){c.info(`Crash report directory not available.`),n&&c.out([]);return}let r;try{r=Y.readdirSync(t.localDir)}catch{c.info(`No crash reports found.`),n&&c.out([]);return}let i=orderAndLimitCrashReports(r,{order:e.order,limit:e.limit});if(i.length===0){c.info(`No crash reports found.`),n&&c.out([]);return}if(n){c.out(formatCrashReportFiles(i,t.localDir));return}c.info(`${i.length} crash report(s) in ${t.localDir}:`);for(let e of i)c.log(` ${e}`)}}),Mi=O({name:`send`,description:`Submit a crash report to help improve the SDK.`,args:q.strictObject({file:W(q.string(),{description:`Path to the crash report file`,required:!0,completion:{type:`file`,extensions:[`log`]}})}),run:async e=>{let t;try{t=Y.readFileSync(e.file,`utf-8`)}catch{c.error(`Crash report file not found: ${e.file}`),process.exit(1)}let n=parseCrashLogFile(t);n||(c.error(`Failed to parse crash report file. The file may be corrupted.`),process.exit(1));let r=await Cr();c.info(`Sending crash report...`),await Pr(n,r)?c.success(`Crash report submitted successfully. Thank you!`):(c.error(`Failed to submit crash report. The server may be unavailable.`),process.exit(1))}});function parseCrashLogFile(e){try{let t=e.replace(/\r\n/g,`
4
4
  `),n=`\n${jr}\n`,r=t.lastIndexOf(n);if(r===-1)return;let i=t.slice(r+n.length).split(`
5
5
  `)[0];return i?JSON.parse(i):void 0}catch{return}}const Ni=G({name:`crashreport`,description:`Manage crash reports.`,subCommands:{list:ji,send:Mi},async run(){await b(ji)}}),Pi=O({name:`deploy`,description:`Deploy your application by applying the Tailor configuration.`,args:q.strictObject({...R,...ke,...C,"create-workspace":W(q.boolean().optional(),{description:`Create a workspace when the account has none`}),"workspace-name":W(q.string().optional(),{description:`Name for a workspace created during deploy`}),"workspace-region":W(q.string().optional(),{description:`Region for a workspace created during deploy`}),"organization-id":W(q.string().optional(),{description:`Organization ID for a workspace created during deploy`,env:`TAILOR_PLATFORM_ORGANIZATION_ID`}),"folder-id":W(q.string().optional(),{description:`Folder ID for a workspace created during deploy`,env:`TAILOR_PLATFORM_FOLDER_ID`}),"dry-run":W(q.boolean().optional(),{alias:`d`,description:`Run the command without making any changes`}),"no-schema-check":W(q.boolean().optional(),{description:`Skip schema diff check against migration snapshots`}),"no-validate":W(q.boolean().optional(),{description:`Skip client-side validation against platform resource constraints`}),"no-cache":W(q.boolean().optional(),{description:`Disable bundle caching for this run`}),"clean-cache":W(q.boolean().optional(),{description:`Clean the bundle cache before building`})}),run:async e=>{await A({profile:e.profile});let{initTelemetry:t}=await import(`../telemetry-DXHP3VVi.mjs`);await t(),await Tn({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})}}),Fi=G({name:`executor`,description:`Manage executors`,subCommands:{trigger:De,jobs:$e,list:Hn,get:gn,webhook:_e},async run(){await b(Hn)}});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 Ii=/^\s+at\s+(?:(.+?)\s+\()?(file:\/\/\/.+?):(\d+):(\d+)\)?$/;function parseStackTrace(e){let t=e.split(`
@@ -83,9 +83,9 @@ Error:`));let e=formatErrorWithSourcemap(b.error,m,process.cwd());e?c.log(e):c.l
83
83
  No profiles found.
84
84
  Please create a profile first using 'tailor profile create' command.
85
85
  `),t&&c.out([]);return}let r=n.map(([e,t])=>{let n=o(t,`profile entry "${e}" is undefined`);return{name:e,user:n.user,workspaceId:n.workspace_id,permission:n.readonly===!0?`read`:`write`,...n.machine_user?{machineUser:n.machine_user,machineUserOverride:n.machine_user_override??`allow`}:{},...n.platform_url?{platformUrl:n.platform_url}:{},...n.oauth2_client_id?{oauth2ClientId:n.oauth2_client_id}:{},...n.console_url?{consoleUrl:n.console_url}:{}}});c.out(r)}}),da=O({name:`update`,description:`Update profile properties.`,args:q.strictObject({name:W(q.string(),{positional:!0,description:`Profile name`}),user:W(q.string().optional(),{alias:`u`,description:`New user email address or machine user client ID`}),"workspace-id":W(q.string().optional(),{alias:`w`,description:`New workspace ID`}),permission:W(q.enum([`write`,`read`]).optional(),{description:`Profile permission. 'read' blocks all write commands; 'write' lifts the restriction.`}),"machine-user":W(q.string().optional(),{alias:`m`,description:`Default machine user name for application-data commands (query, workflow start, function run, machineuser token). Pass an empty string to clear.`}),"machine-user-override":W(q.enum([`allow`,`deny`]).optional(),{description:`Whether the command line or TAILOR_PLATFORM_MACHINE_USER_NAME may override the profile's machine user. 'deny' requires --machine-user; 'allow' lifts the restriction.`}),"platform-url":W(q.union([q.url(),q.literal(``)]).optional(),{description:`Platform API base URL for this profile. Pass an empty string to clear.`}),"oauth2-client-id":W(q.string().optional(),{description:`OAuth2 client ID for logging in to this profile's platform. Pass an empty string to clear.`}),"console-url":W(q.union([q.url(),q.literal(``)]).optional(),{description:`Console base URL for this profile. Pass an empty string to clear.`})}),run:async e=>{let t=await M(),n=t.profiles[e.name];if(!n)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${e.name}" not found.`});if(!e.user&&!e[`workspace-id`]&&e.permission===void 0&&e[`machine-user`]===void 0&&e[`machine-user-override`]===void 0&&e[`platform-url`]===void 0&&e[`oauth2-client-id`]===void 0&&e[`console-url`]===void 0)throw U({code:`PROFILE_UPDATE_EMPTY`,message:`Please provide at least one property to update.`,command:`profile update`});let r=n.user,i=e.user||r,a=n.workspace_id,o=e[`workspace-id`]||a,s=i,l=e[`machine-user`]===``?void 0:e[`machine-user`]??n.machine_user,u=e[`machine-user-override`]===`allow`?void 0:e[`machine-user-override`]??n.machine_user_override,d=e[`platform-url`]===``?void 0:e[`platform-url`]??n.platform_url,f=e[`oauth2-client-id`]===``?void 0:e[`oauth2-client-id`]??n.oauth2_client_id,p=e[`console-url`]===``?void 0:e[`console-url`]??n.console_url,m={...d?{platformUrl:d}:{},...f?{oauth2ClientId:f}:{},...p?{consoleUrl:p}:{}},h=Object.keys(m).length>0?m:void 0,g=e[`platform-url`]===``?P(n):h;if((e[`machine-user`]!==void 0||e[`machine-user-override`]!==void 0)&&u===`deny`&&!l)throw e[`machine-user-override`]===`deny`?U({code:`PROFILE_OPTIONS_INVALID`,message:`--machine-user-override deny requires --machine-user.`,command:`profile update`}):U({code:`PROFILE_OPTIONS_INVALID`,message:`Cannot clear the machine user while machine-user-override is "deny". Also pass --machine-user-override allow.`,command:`profile update`});if(e.user!==void 0||e[`workspace-id`]!==void 0||e[`platform-url`]!==void 0){let n=await dn(t,i,g,e.name);s=n.user;let r=await cr(n.accessToken,h);if(!(await er(async(e,t)=>{let{workspaces:n,nextPageToken:i}=await r.listWorkspaces({pageToken:e,pageSize:t});return[n,i]})).find(e=>e.id===o))throw U({code:`WORKSPACE_NOT_FOUND`,message:`Workspace "${o}" not found.`})}n.user=s,n.workspace_id=o,e.permission===`read`?n.readonly=!0:e.permission===`write`&&delete n.readonly,e[`machine-user`]!==void 0&&(e[`machine-user`]===``?delete n.machine_user:n.machine_user=e[`machine-user`]),e[`machine-user-override`]===`deny`?n.machine_user_override=`deny`:e[`machine-user-override`]===`allow`&&delete n.machine_user_override,e[`platform-url`]!==void 0&&(e[`platform-url`]===``?delete n.platform_url:n.platform_url=e[`platform-url`]),e[`oauth2-client-id`]!==void 0&&(e[`oauth2-client-id`]===``?delete n.oauth2_client_id:n.oauth2_client_id=e[`oauth2-client-id`]),e[`console-url`]!==void 0&&(e[`console-url`]===``?delete n.console_url:n.console_url=e[`console-url`]),L(t),e.json||c.success(`Profile "${e.name}" updated successfully`);let _={name:e.name,user:s,workspaceId:o,permission:n.readonly===!0?`read`:`write`,...n.machine_user?{machineUser:n.machine_user,machineUserOverride:n.machine_user_override??`allow`}:{},...n.platform_url?{platformUrl:n.platform_url}:{},...n.oauth2_client_id?{oauth2ClientId:n.oauth2_client_id}:{},...n.console_url?{consoleUrl:n.console_url}:{}};c.out(_)}}),fa=G({name:`profile`,description:`Manage workspace profiles (user + workspace combinations).`,subCommands:{create:ca,delete:la,list:ua,update:da},async run(){await b(ua)}}),pa={"vault-name":W(q.string(),{alias:`V`,description:`Vault name`})},ma={...pa,name:W(q.string(),{alias:`n`,description:`Secret name`})},ha={...ma,value:W(q.string(),{alias:`v`,description:`Secret value`})};async function checkVaultManaged(e){let{client:t,workspaceId:n,vaultName:r}=e,i=E(n,`vault`,r),a={isManaged:!1,trn:i,existingLabels:{}},o,s;try{let{metadata:e}=await t.getMetadata({trn:i});s=e?.labels??{},o=s[be]}catch{return a}return o?(c.warn(`Vault "${r}" is managed by defineSecretManager() in tailor.config.ts (owner: "${o}"). Changes made via CLI may conflict with the config on the next apply.`),{isManaged:!0,trn:i,existingLabels:s}):a}async function releaseVaultOwnership(e){let{client:t,trn:n}=e;await ot(t,{trn:n,remove:[be,ut,un]}),c.info(`Config ownership has been removed from this vault. Remove it from defineSecretManager() in your config to prevent the next apply from re-claiming it.`)}const ga=O({name:`create`,description:`Create a secret in a vault.`,args:q.strictObject({...R,...ha,...C}),run:async e=>{c.registerSecret(e.value),await A({profile:e.profile});let{client:t,workspaceId:n}=await D({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e[`vault-name`]});if(!r.isManaged||e.yes||await k.confirm({message:`Do you want to proceed?`,default:!1})){try{await t.createSecretManagerSecret({workspaceId:n,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name,secretmanagerSecretValue:e.value})}catch(t){if(t instanceof Q){if(t.code===Z.NotFound)throw U({code:`VAULT_NOT_FOUND`,message:`Vault "${e[`vault-name`]}" not found.`,cause:t});if(t.code===Z.AlreadyExists)throw U({code:`SECRET_EXISTS`,message:`Secret "${e.name}" already exists.`,cause:t})}throw t}r.isManaged&&await releaseVaultOwnership({client:t,...r}),c.success(`Secret: ${e.name} created in vault: ${e[`vault-name`]}`)}}}),_a=O({name:`delete`,description:`Delete a secret in a vault.`,args:q.strictObject({...R,...ma,...C}),run:async e=>{await A({profile:e.profile});let{client:t,workspaceId:n}=await D({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e[`vault-name`]});if(!e.yes&&await k.text({message:`Enter the secret name to confirm deletion ("${e.name}"):`})!==e.name){c.info(`Secret deletion cancelled.`);return}try{await t.deleteSecretManagerSecret({workspaceId:n,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`SECRET_NOT_FOUND`,message:`Secret "${e.name}" not found in vault "${e[`vault-name`]}".`,cause:t}):t}r.isManaged&&await releaseVaultOwnership({client:t,...r}),c.success(`Secret: ${e.name} deleted from vault: ${e[`vault-name`]}`)}});function secretInfo(e){return{name:e.name,createdAt:e.createTime?X(e.createTime):null,updatedAt:e.updateTime?X(e.updateTime):null}}async function secretList(e){let{client:t,workspaceId:n}=await D({profile:e.profile,workspaceId:e.workspaceId}),r=Ue(e.order);return(await B(async(i,a)=>{let{secrets:o,nextPageToken:s}=await t.listSecretManagerSecrets({workspaceId:n,secretmanagerVaultName:e.vaultName,pageToken:i,pageSize:a,pageDirection:r});return[o,s]},{limit:e.limit})).map(secretInfo)}const va=O({name:`list`,description:`List all secrets in a vault.`,args:q.strictObject({...R,...pa,...Re()}),run:async e=>{try{let t=await secretList({workspaceId:e[`workspace-id`],profile:e.profile,vaultName:e[`vault-name`],order:e.order,limit:e.limit});c.out(t)}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`VAULT_NOT_FOUND`,message:`Vault "${e[`vault-name`]}" not found.`,cause:t}):t}}}),ya=O({name:`update`,description:`Update a secret in a vault.`,args:q.strictObject({...R,...ha,...C}),run:async e=>{c.registerSecret(e.value),await A({profile:e.profile});let{client:t,workspaceId:n}=await D({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e[`vault-name`]});if(!r.isManaged||e.yes||await k.confirm({message:`Do you want to proceed?`,default:!1})){try{await t.updateSecretManagerSecret({workspaceId:n,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name,secretmanagerSecretValue:e.value})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`SECRET_NOT_FOUND`,message:`Secret "${e.name}" not found in vault "${e[`vault-name`]}".`,cause:t}):t}r.isManaged&&await releaseVaultOwnership({client:t,...r}),c.success(`Secret: ${e.name} updated in vault: ${e[`vault-name`]}`)}}}),ba={name:W(q.string(),{positional:!0,description:`Vault name`})},xa=O({name:`create`,description:`Create a new Secret Manager vault.`,args:q.strictObject({...R,...ba}),run:async e=>{await A({profile:e.profile});let{client:t,workspaceId:n}=await D({profile:e.profile,workspaceId:e[`workspace-id`]});try{await t.createSecretManagerVault({workspaceId:n,secretmanagerVaultName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.AlreadyExists?U({code:`VAULT_EXISTS`,message:`Vault "${e.name}" already exists.`,cause:t}):t}c.success(`Vault: ${e.name} created`)}}),Sa=O({name:`delete`,description:`Delete a Secret Manager vault.`,args:q.strictObject({...R,...ba,...C}),run:async e=>{await A({profile:e.profile});let{client:t,workspaceId:n}=await D({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e.name});if(!e.yes&&await k.text({message:`Enter the vault name to confirm deletion ("${e.name}"):`})!==e.name){c.info(`Vault deletion cancelled.`);return}try{await t.deleteSecretManagerVault({workspaceId:n,secretmanagerVaultName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`VAULT_NOT_FOUND`,message:`Vault "${e.name}" not found.`,cause:t}):t}r.isManaged&&c.info(`Remove this vault from defineSecretManager() in your config to prevent the next apply from re-creating it.`),c.success(`Vault: ${e.name} deleted`)}});function vaultInfo(e){return{name:e.name,createdAt:e.createTime?X(e.createTime):null,updatedAt:e.updateTime?X(e.updateTime):null}}async function vaultList(e){let{client:t,workspaceId:n}=await D({profile:e?.profile,workspaceId:e?.workspaceId}),r=Ue(e?.order);return(await B(async(e,i)=>{let{vaults:a,nextPageToken:o}=await t.listSecretManagerVaults({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e?.limit})).map(vaultInfo)}const Ca=O({name:`list`,description:`List all Secret Manager vaults in the workspace.`,args:q.strictObject({...R,...Re()}),run:async e=>{let t=await vaultList({workspaceId:e[`workspace-id`],profile:e.profile,order:e.order,limit:e.limit});c.out(t)}}),wa=G({name:`vault`,description:`Manage Secret Manager vaults.`,subCommands:{create:xa,delete:Sa,list:Ca},async run(){await b(Ca)}}),Ta=G({name:`secret`,description:`Manage Secret Manager vaults and secrets.`,subCommands:{vault:wa,create:ga,update:ya,list:va,delete:_a},async run(){await b(wa)}}),Ea={[t.UNSPECIFIED]:`unspecified`,[t.PENDING]:`pending`,[t.VERIFYING]:`verifying`,[t.CERT_ISSUED]:`cert_issued`,[t.ACTIVE]:`active`,[t.FAILED]:`failed`},Da=O({name:`get`,description:`Get details of a custom domain.`,args:q.strictObject({...R,domain:W(q.string(),{positional:!0,description:`Custom domain name`})}),run:async e=>{let{client:t,workspaceId:n}=await D({profile:e.profile,workspaceId:e[`workspace-id`]}),r=`Custom domain "${e.domain}" not found.`;try{let{customDomain:i}=await t.getCustomDomain({workspaceId:n,domain:e.domain});if(!i)throw U({code:`STATIC_WEBSITE_DOMAIN_NOT_FOUND`,message:r});let a={domain:i.domain,status:Ea[i.status]??`unknown`,trafficCnameTarget:i.trafficCnameTarget,certificateCnameTarget:i.certificateCnameTarget,errorMessage:i.errorMessage||void 0};c.out(a)}catch(e){throw e instanceof Q&&e.code===Z.NotFound?U({code:`STATIC_WEBSITE_DOMAIN_NOT_FOUND`,message:r,cause:e}):e}}}),Oa=O({name:`list`,description:`List custom domains for a static website.`,args:q.strictObject({...R,name:W(q.string(),{positional:!0,description:`Static website name`})}),run:async e=>{let{client:t,workspaceId:n}=await D({profile:e.profile,workspaceId:e[`workspace-id`]});try{let{customDomains:r}=await t.listCustomDomains({workspaceId:n,staticWebsiteName:e.name});if(r.length===0){c.info(`No custom domains found.`),c.jsonMode&&c.out([]);return}let i=r.map(e=>({domain:e.domain,status:Ea[e.status]??`unknown`,trafficCnameTarget:e.trafficCnameTarget,certificateCnameTarget:e.certificateCnameTarget}));c.out(i)}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`STATIC_WEBSITE_NOT_FOUND`,message:`Static website "${e.name}" not found.`,cause:t}):t}}}),ka=G({name:`domain`,description:`Manage custom domains for static websites.`,subCommands:{list:Oa,get:Da}}),Aa=O({name:`get`,description:`Get details of a specific static website.`,args:q.strictObject({...R,name:W(q.string(),{positional:!0,description:`Static website name`})}),run:async e=>{let{client:t,workspaceId:n}=await D({profile:e.profile,workspaceId:e[`workspace-id`]}),r=`Static website "${e.name}" not found.`;try{let{staticwebsite:i}=await t.getStaticWebsite({workspaceId:n,name:e.name});if(!i)throw U({code:`STATIC_WEBSITE_NOT_FOUND`,message:r});let a={workspaceId:n,name:i.name,description:i.description,url:i.url,allowedIpAddresses:e.json?i.allowedIpAddresses:i.allowedIpAddresses.join(`
86
- `)};c.out(a)}catch(e){throw e instanceof Q&&e.code===Z.NotFound?U({code:`STATIC_WEBSITE_NOT_FOUND`,message:r,cause:e}):e}}});async function listStaticWebsites(e){let{client:t,workspaceId:n}=await D({profile:e?.profile,workspaceId:e?.workspaceId}),r=Ue(e?.order);return(await B(async(e,i)=>{let{staticwebsites:a,nextPageToken:o}=await t.listStaticWebsites({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e?.limit})).map(e=>({workspaceId:n,name:e.name,description:e.description,url:e.url,allowedIpAddresses:e.allowedIpAddresses}))}const ja=O({name:`list`,description:`List all static websites in a workspace.`,args:q.strictObject({...R,...Re()}),run:async e=>{let t=c.jsonMode,n=await listStaticWebsites({workspaceId:e[`workspace-id`],profile:e.profile,order:e.order,limit:e.limit}),r=t?n:n.map(({allowedIpAddresses:e,...t})=>{if(e.length===0)return{...t,allowedIpAddresses:`No allowed IP addresses`};let n=e.length,r=n===1?`1 IP address`:`${n} IP addresses`;return{...t,allowedIpAddresses:r}});c.out(r)}}),Ma=G({name:`staticwebsite`,description:`Manage static websites in your workspace.`,subCommands:{deploy:Xe,domain:ka,list:ja,get:Aa},async run(){await b(ja)}}),Na=new Set(Object.values(xt));async function activateBaseline(e,t,n,r){let i=await $.realpath(e),a=K.dirname(i),o=K.basename(i),s=await $.mkdtemp(K.join(a,`.${o}-rebaseline-`)),l=`${s}-previous`,u=!1,d=!1;try{await $.cp(i,s,{recursive:!0});for(let e of await $.readdir(s,{withFileTypes:!0})){if(!e.isDirectory()||!In.test(e.name))continue;let t=K.join(s,e.name);(await $.readdir(t)).some(e=>Na.has(e))&&await $.rm(t,{recursive:!0,force:!0})}let e={...t,namespace:n,version:6,createdAt:new Date().toISOString(),rebaseline:r},a=await et(e,s,0);g(a.filePath),await $.rename(i,l),u=!0;try{await $.rename(s,i),d=!0}catch(e){throw await $.rename(l,i),u=!1,e}try{await $.rm(l,{recursive:!0,force:!0})}catch(e){c.warn(`The previous migration directory remains at ${l}: ${e instanceof Error?e.message:String(e)}`)}u=!1}finally{Y.existsSync(s)&&await $.rm(s,{recursive:!0,force:!0}),!d&&u&&Y.existsSync(l)&&await $.rename(l,i)}}async function rebaseline(e){fe(`tailordb migration`);let{config:t,plugins:n}=await I(e.configPath),r=K.dirname(t.path),i=Vt(F(t,r),e.namespace),a=Tr({command:`tailor`,args:[`tailordb`,`migration`,`generate`,`--config`,t.path]});Dt(i.migrationsDir,i.namespace);let o=j(i.migrationsDir);if(!o)throw U({code:`MIGRATION_HISTORY_NOT_FOUND`,message:`No migration history found for namespace "${i.namespace}".`,suggestion:`Run ${a} first.`});let l=Nn(i.migrationsDir),u=j(i.migrationsDir,0)?.rebaseline?.historyId??null,d=an([i])[i.namespace],f=n.length>0?new Ir(n):void 0,{defineApplication:p}=await import(`../application-Dl94fzpm.mjs`),m=p({config:t,pluginManager:f});for(let e of m.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let h=m.tailorDBServices.find(e=>e.namespace===i.namespace);if(!h)throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${i.namespace}"`});let assertLocalTypesReady=()=>{let e=Yt(h.types,i.namespace),t=ge(o,e.tables,i.namespace);if(it(t))throw c.error(`Migration history does not reproduce the current local schema for namespace ${s.bold(i.namespace)}:`),c.log(Qe(t)),U({code:`MIGRATION_HISTORY_MISMATCH`,message:`Refusing to re-baseline: the migration history must reproduce the current local schema.`,suggestion:`Run ${a} first.`})},localSourceFiles=()=>[t.path,...yr(h.config,r)];assertLocalTypesReady();let g=gt(localSourceFiles()),{client:_,workspaceId:v}=await D({profile:e.profile,workspaceId:e.workspaceId}),b=[`--config`,t.path,...T({workspaceId:v,profile:e.profile})],x=Tr({command:`tailor`,args:[`tailordb`,`migration`,`set`,`0`,`--namespace`,i.namespace,...b]}),ee=Tr({command:`tailor`,args:[`deploy`,...b]}),assertConnectedWorkspaceReady=async(e,n)=>{let r=await xn(_,E(v,`tailordb`,i.namespace)),a=r.number;if(a!==l){let e=a===null?`<unset>`:y(a);throw U({code:`REBASELINE_CHECKPOINT_BEHIND`,message:`The connected workspace must be at the latest migration ${y(l)} before re-baselining; current checkpoint is ${e}.`})}if(r.historyIdInvalid)throw U({code:`REBASELINE_REMOTE_HISTORY_INVALID`,message:`Refusing to re-baseline: the connected workspace has an invalid migration history marker.`});if(r.historyId!==e)throw U(n===`confirmation`?{code:`REBASELINE_STATE_CHANGED`,message:`The connected workspace migration history changed while waiting for confirmation.`,suggestion:`Run the command again.`}:{code:`REBASELINE_REMOTE_HISTORY_MISMATCH`,message:`Refusing to re-baseline: the connected workspace does not match the local migration history.`});let o=await Ce(_,v,[i],t,[ue(h)]),s=o[0];if(!s||s.remoteMigrationNumber!==l||s.hasDrift||s.checkpointMissingLocal)throw s?.hasDrift&&(c.error(`Remote schema drift detected:`),c.log(pe(o))),U({code:`REBASELINE_REMOTE_SCHEMA_MISMATCH`,message:`Refusing to re-baseline: the connected workspace remote schema must match the latest migration.`})};if(await assertConnectedWorkspaceReady(u,`initial`),c.newline(),c.warn(`This will replace the migration history for ${s.bold(i.namespace)}.`),c.log(` Latest migration: ${y(l)}`),c.log(` New history: 0000/schema.json only`),c.log(` migrate.ts and db.ts files will disappear from the working tree.`),c.log(` Committed migration files will remain in Git history. Preserve any uncommitted files before continuing.`),c.log(` Every other environment must already be at the latest migration.`),c.log(` The connected workspace checkpoint will be reset to 0000.`),c.newline(),!e.yes&&!await k.confirm({message:`Re-baseline this migration history and reset the connected workspace checkpoint?`,default:!1})){c.info(`Operation cancelled.`);return}if(Dt(i.migrationsDir,i.namespace),an([i])[i.namespace]!==d)throw U({code:`REBASELINE_STATE_CHANGED`,message:`Migration files changed while waiting for confirmation.`,suggestion:`Run the command again.`});if(gt(localSourceFiles())!==g)throw U({code:`REBASELINE_STATE_CHANGED`,message:`Local TailorDB table or config files changed.`,suggestion:`Run the command again.`});assertLocalTypesReady(),await assertConnectedWorkspaceReady(u,`confirmation`);let S={historyId:Ne(),replacedHistoryId:u,replacedLatestMigration:l};await activateBaseline(i.migrationsDir,o,i.namespace,S);try{await ye(_,v,i.namespace,0,S.historyId)}catch(e){throw U({code:`REBASELINE_CHECKPOINT_UPDATE_FAILED`,message:`The local migration history was re-baselined, but the connected workspace checkpoint could not be updated.`,suggestion:`Run ${x}, or run ${ee} with schema checks enabled after resolving the connection error.`,cause:e})}c.success(`Re-baselined ${s.bold(i.namespace)} and reset the connected workspace checkpoint to 0000.`)}const Pa=O({name:`rebaseline`,description:`Collapse the full migration history into a new 0000 baseline.`,notes:`Re-baselining removes migrations after 0000 from the working tree, records a new migration history ID, and resets the connected workspace checkpoint without changing its schema or data. Every environment must already have applied the latest migration before you run this command.`,args:q.strictObject({...N,...C,namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await A({profile:e.profile}),await rebaseline({configPath:e.config,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile})}});async function set(e){fe(`tailordb migration`);let t=nt(e.number),{config:n}=await I(e.configPath),r=K.dirname(n.path),i=F(n,r),a=Vt(i,e.namespace),o=a.namespace;Dt(a.migrationsDir,o),ee(a.migrationsDir,t);let l=j(a.migrationsDir,0)?.rebaseline?.historyId,{client:u,workspaceId:d}=await D({profile:e.profile,workspaceId:e.workspaceId}),f=E(d,`tailordb`,o),p=await xn(u,f),m=p.number,h=m??0,g=p.historyIdInvalid?`<invalid>`:p.historyId??`<unset>`,_=l??`<unset>`;if(c.newline(),c.warn(`This operation will change TailorDB migration state metadata.`),c.log(`Namespace: ${s.bold(o)}`),c.log(`Current migration: ${m===null?`<unset>`:s.bold(y(m))}`),c.log(`New migration: ${s.bold(y(t))}`),c.log(`Current migration history ID: ${s.bold(g)}`),c.log(`New migration history ID: ${s.bold(_)}`),c.newline(),t<h?(c.warn(`Setting migration number backwards (${y(h)} → ${y(t)}) will cause previous migrations to be re-executed on next apply.`),c.newline()):t>h&&(c.warn(`Setting migration number forwards (${y(h)} → ${y(t)}) will skip migrations ${y(h+1)} to ${y(t)}.`),c.newline()),!e.yes){if(!await k.confirm({message:`Continue with migration checkpoint and history ID update?`,default:!1})){c.info(`Operation cancelled.`);return}c.newline()}await ot(u,{trn:f,labels:{[Ae]:le(t),...l?{[Ut]:l}:{}},remove:l?void 0:[Ut]}),c.success(`Migration checkpoint set to ${s.bold(y(t))} for namespace ${s.bold(o)}`)}const Fa=O({name:`set`,description:`Set migration checkpoint to a specific number.`,notes:"The migration number must be a 4-digit value (e.g. `0001`) or a bare integer (e.g. `1`) within 0–9999, and must exist in the local migration history; `0` is always accepted as the baseline, provided the local history passes validation. A gapped history is rejected.\n\nMetadata lookup failures (authentication, permission, or network errors) are reported as errors; only a not-yet-deployed namespace is treated as having no checkpoint.",args:q.strictObject({...N,...C,number:W(q.string(),{positional:!0,description:`Migration number to set (e.g., 0001 or 1)`}),namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await A({profile:e.profile}),await set({configPath:e.config,number:e.number,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile})}});function isStatusFailure(e){return e.status===`error`}async function collectMigrationStatuses(e){let{config:t}=await I(e.configPath),n=K.dirname(t.path),r=F(t,n);if(r.length===0)throw pn();let i=e.namespace?r.filter(t=>t.namespace===e.namespace):r;if(i.length===0)throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`Namespace "${e.namespace}" not found or does not have migrations configured`});let a=new Map,o=new Map;for(let{namespace:e,migrationsDir:t}of i)try{let n=ne(t),r=new Map,i=null;for(let e of n){if(e.type===`schema`){let t=g(e.path);e.number===0&&(i=t.rebaseline?.historyId??null);continue}try{let t=Kt(e.path);t.description&&r.set(e.number,t.description)}catch(e){if(Dr(e)&&e.code===`MIGRATION_FILE_VERSION_UNSUPPORTED`)throw e}}a.set(e,{migrationFiles:n,descriptions:r,historyId:i})}catch(t){o.set(e,Er(t))}if(a.size===0)return i.map(({namespace:e})=>({status:`error`,namespace:e,error:o.get(e)??`Failed to read local migration history.`}));let{client:s,workspaceId:c}=await D({profile:e.profile,workspaceId:e.workspaceId}),l=[];for(let{namespace:e}of i){if(o.has(e)){l.push({status:`error`,namespace:e,error:o.get(e)??`Failed to read local migration history.`});continue}let t=a.get(e);if(!t){l.push({status:`error`,namespace:e,error:`Failed to read local migration history.`});continue}let{migrationFiles:n,descriptions:r,historyId:i}=t,u=E(c,`tailordb`,e),d;try{d=await xn(s,u)}catch(t){l.push({status:`error`,namespace:e,error:t instanceof Error?t.message:String(t)});continue}let f=d.number??0;if(d.historyIdInvalid){l.push({status:`error`,namespace:e,error:`Remote migration history ID is invalid.`});continue}if((d.number!==null||d.historyId!==null)&&d.historyId!==i){l.push({status:`error`,namespace:e,error:`Remote migration history ID ${d.historyId??`<unset>`} does not match local migration history ID ${i??`<unset>`}.`});continue}let p=n.map(e=>e.number).filter((e,t,n)=>n.indexOf(e)===t).toSorted((e,t)=>e-t).filter(e=>e>f).map(e=>({number:e,label:y(e),...r.has(e)?{description:r.get(e)}:{}}));l.push({status:`ok`,namespace:e,currentMigration:f,currentMigrationLabel:y(f),pendingMigrations:p})}return l}function printMigrationStatuses(e){for(let t of e){if(c.newline(),c.info(`Namespace: ${s.bold(t.namespace)}`),isStatusFailure(t)){c.error(` Migration status error: ${t.error}`);continue}if(c.log(` Current migration: ${s.bold(t.currentMigrationLabel)}`),t.pendingMigrations.length>0){c.log(` Pending migrations:`);for(let e of t.pendingMigrations)e.description?c.log(` - ${e.label}: ${e.description}`):c.log(` - ${e.label}`)}else c.log(` Pending migrations: (none)`)}c.newline()}async function status(e){fe(`tailordb migration`);let t=await collectMigrationStatuses(e);e.json?c.out(t):printMigrationStatuses(t);let n=t.filter(isStatusFailure);if(n.length>0){let e=n.map(e=>e.namespace).join(`, `);throw U({code:`MIGRATION_STATUS_FAILED`,message:`Migration status check failed for ${n.length} namespace${n.length===1?``:`s`}: ${e}`})}}const Ia=O({name:`status`,description:`Show the current migration status for TailorDB namespaces, including applied and pending migrations.`,notes:`Every local migration file is checked for a compatible format version, and deployed migration history IDs must match the local baseline. Compatibility errors, history mismatches, and metadata lookup failures are reported per namespace and make the command exit non-zero; only a not-yet-deployed namespace is treated as having no applied migrations.`,args:q.strictObject({...N,namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (shows all namespaces if not specified)`})}),run:async e=>{await status({configPath:e.config,namespace:e.namespace,workspaceId:e[`workspace-id`],profile:e.profile,json:c.jsonMode})}});async function fetchRemoteGqlPermissions(e,t,n){return nr(async(r,i)=>{let{permissions:a,nextPageToken:o}=await e.listTailorDBGQLPermissions({workspaceId:t,namespaceName:n,pageToken:r,pageSize:i});return[a,o]})}async function fetchRemoteTypes(e,t,n){return er(async(r,i)=>{try{let{tailordbTypes:a,nextPageToken:o}=await e.listTailorDBTypes({workspaceId:t,namespaceName:n,pageToken:r,pageSize:i});return[a,o]}catch(e){throw e instanceof Q&&e.code===Z.NotFound?U({code:`MIGRATION_NAMESPACE_NOT_DEPLOYED`,message:`Cannot sync: TailorDB namespace "${n}" has not been deployed yet.`,suggestion:`Deploy the namespace before syncing its migration history.`,cause:e}):e}})}async function assertMigrationsReproduceLocalTypes(e,t){let{config:n,plugins:r}=e,i=r.length>0?new Ir(r):void 0,{defineApplication:a,generatePluginFilesIfNeeded:o}=await import(`../application-Dl94fzpm.mjs`),l=a({config:n,pluginManager:i}),u=l.tailorDBServices.find(e=>e.namespace===t.namespace);if(!u)throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${t.namespace}"`});for(let e of l.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let d=o(i,l.tailorDBServices,n.path),f=l.executorService??(d.length>0?(await import(`../service-B3OiWCYg.mjs`)).createExecutorService({config:{files:[]},baseDir:K.dirname(n.path)}):void 0);await f?.loadExecutors(),d.length>0&&await f?.loadPluginExecutorFiles([...d]);let p=new Set;for(let e of Object.values(f?.executors??{}))de(e)&&e.trigger.kind===`tailordb`&&p.add(e.trigger.tableName);let m={executorUsedTables:p,namespaceGqlOperations:u.config.gqlOperations},h=j(t.migrationsDir);if(!h)return m;let g=Yt(u.types,t.namespace),_=ge(h,g.tables,t.namespace);if(!it(_))return m;throw c.error(`Migration history does not reproduce the current local schema for namespace ${s.bold(t.namespace)}:`),c.log(Qe(_)),c.newline(),c.info(`This usually means one of the following:`),c.info(` - Migration files were edited and replaying them no longer matches the table definitions — fix the migration files.`,{mode:`plain`}),c.info(` - Table definitions changed without a new migration — run 'tailor tailordb migration generate' first.`,{mode:`plain`}),c.newline(),U({code:`MIGRATION_HISTORY_MISMATCH`,message:`Refusing to sync: the migration history must reproduce the current local schema before it can be applied to the remote.`,suggestion:`Generate a migration for the pending schema changes first.`})}async function sync(e){fe(`tailordb migration`);let t=nt(e.number),n=await I(e.configPath),{config:r}=n,i=K.dirname(r.path),a=F(r,i),o=Vt(a,e.namespace);Dt(o.migrationsDir,o.namespace);let l=ee(o.migrationsDir,t),u=j(o.migrationsDir,t);if(!u)throw U({code:`MIGRATION_BASELINE_NOT_FOUND`,message:`No initial schema snapshot found in ${o.migrationsDir}. Expected 0000/schema.json.`,suggestion:`Create the initial schema snapshot first.`});let f=await assertMigrationsReproduceLocalTypes(n,o),{client:p,workspaceId:m}=await D({profile:e.profile,workspaceId:e.workspaceId}),h=E(m,`tailordb`,o.namespace),g=await At(p,h),_=await fetchRemoteTypes(p,m,o.namespace),v=new Set(_.map(e=>e.name)),{creates:b,updates:x,deletes:S}=dt(u,v),te=await fetchRemoteGqlPermissions(p,m,o.namespace),C=new Set(te.map(e=>e.typeName)),w=Object.entries(u.tables).flatMap(([e,t])=>t.permissions?.gql?[{typeName:e,permission:d(t.permissions.gql)}]:[]),ne=new Set(w.map(e=>e.typeName)),re=te.filter(e=>!ne.has(e.typeName));if(c.newline(),c.info(`Namespace: ${s.bold(o.namespace)}`),c.log(` Current migration: ${g===null?`<unset>`:s.bold(y(g))}`),c.log(` Target migration: ${s.bold(y(t))}`),c.log(` Tables to create: ${s.bold(String(b.length))}`),c.log(` Tables to update: ${s.bold(String(x.length))}`),c.log(` Tables to delete: ${s.bold(String(S.length))}`),c.log(` GQL permissions to set: ${s.bold(String(w.length))}`),c.log(` GQL permissions to delete: ${s.bold(String(re.length))}`),c.newline(),b.length+x.length+S.length+w.length+re.length===0?c.info(`No tables to apply; only the migration label will be updated.`):(c.warn(`This operation will overwrite remote TailorDB tables to match the selected snapshot.`),S.length>0&&c.warn(`Existing data in deleted tables will be lost.`),c.newline()),c.warn(`Sync never runs migrate.ts scripts; it only applies the schema snapshot and moves the migration label.`),c.newline(),g!==null&&t<g?(c.warn(`Migrations ${y(t+1)}–${y(g)} will become pending again and re-execute on the next deploy, including their migrate.ts scripts. Make sure those scripts are idempotent (safe to re-run).`),c.newline()):g!==null&&t>g&&(c.warn(`Moving the migration label forwards (${y(g)} → ${y(t)}): migrate.ts scripts for migrations ${y(g+1)}–${y(t)} will not run on the next deploy.`),c.newline()),!e.yes){if(!await k.confirm({message:`Continue and set migration label to ${y(t)}?`,default:!1})){c.info(`Operation cancelled.`);return}c.newline()}let ie=Ve(u,f),manifestFor=e=>{let t=ie.get(e);if(!t)throw H(`Internal error: no manifest generated for table "${e}". No changes were applied.`);return t},ae=b.map(e=>manifestFor(e)),oe=x.map(e=>manifestFor(e));try{await Promise.all([...ae.map(e=>p.createTailorDBType({workspaceId:m,namespaceName:o.namespace,tailordbType:e})),...oe.map(e=>p.updateTailorDBType({workspaceId:m,namespaceName:o.namespace,tailordbType:e}))])}catch(e){ze(e,[`The target snapshot marks a field as required, but existing remote records have no value for it.`,`Populate those records first (e.g. with a migration script applied via 'tailor deploy'), then re-run the sync.`])}await Promise.all(w.map(({typeName:e,permission:t})=>{let n={workspaceId:m,namespaceName:o.namespace,typeName:e,permission:t};return C.has(e)?p.updateTailorDBGQLPermission(n):p.createTailorDBGQLPermission(n)})),await Promise.all(re.map(e=>p.deleteTailorDBGQLPermission({workspaceId:m,namespaceName:o.namespace,typeName:e.typeName}))),await Promise.all(S.map(e=>p.deleteTailorDBType({workspaceId:m,namespaceName:o.namespace,tailordbTypeName:e}))),await ot(p,{trn:h,labels:{[Ae]:le(t),...u.rebaseline?.historyId?{[Ut]:u.rebaseline.historyId}:{}},remove:u.rebaseline?.historyId?void 0:[Ut]}),c.success(`Synced namespace ${s.bold(o.namespace)} to migration ${s.bold(y(t))}.`),t<l&&(c.newline(),c.info(`Run 'tailor deploy' to apply migrations ${y(t+1)}–${y(l)} from the working tree.`))}const La=O({name:`sync`,description:`Sync remote TailorDB schema to a specific migration snapshot (recovery from --no-schema-check drift).`,args:q.strictObject({...N,...C,number:W(q.string(),{positional:!0,description:`Migration number to sync to (e.g., 0001 or 1; 0 targets the baseline snapshot)`}),namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await A({profile:e.profile}),await sync({configPath:e.config,number:e.number,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile})}});function delay(e){return e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve()}function assertSeedDataDirectory(e){let t;try{t=Y.statSync(e)}catch(t){throw t.code===`ENOENT`?U({code:`SEED_DATA_NOT_FOUND`,message:`Seed data directory not found: ${e}.`,suggestion:`Generate seed data before testing migrations.`,cause:t}):t}if(!t.isDirectory())throw U({code:`SEED_DATA_INVALID`,message:`Seed data path is not a directory: ${e}`})}function assertAssertionScript(e){let t=K.resolve(e),n;try{n=Y.statSync(t)}catch(e){throw e.code===`ENOENT`?U({code:`MIGRATION_ASSERTION_SCRIPT_NOT_FOUND`,message:`Migration assertion script not found: ${t}`,cause:e}):e}if(!n.isFile())throw U({code:`MIGRATION_ASSERTION_SCRIPT_INVALID`,message:`Migration assertion path is not a file: ${t}`})}function assertCloneTargetRegion(e,t){if(e!==t)throw U({code:`MIGRATION_TEST_REGION_MISMATCH`,message:`Clone mode requires source and target workspaces in the same region (source: ${e}, target: ${t}).`})}function assertTargetWorkspaceDiffers(e,t){if(t?.toLowerCase()===e.toLowerCase())throw U({code:`MIGRATION_TEST_TARGET_INVALID`,message:`The migration test target workspace must differ from the source workspace.`,command:`tailordb migration test`})}function resolveAssertionNamespace(e,t){let n=t??(e.length===1?e[0]:void 0);if(!n)throw U({code:`MIGRATION_TEST_ASSERT_NAMESPACE_REQUIRED`,message:`--assert-namespace is required when pending migrations span multiple namespaces.`,command:`tailordb migration test`});if(!e.includes(n))throw U({code:`MIGRATION_TEST_NO_PENDING_MIGRATIONS`,message:`Assertion namespace "${n}" has no pending migrations.`});return n}async function createMigrationTestBaselineSnapshots(e){let t=new Map([...e.baselines].map(([e,t])=>[e,t.snapshot]));if(e.dataMode!==`clone`)return t;let n=e.inputs.filter(e=>!t.has(e.namespace)),r=await Promise.all(n.map(t=>tt(e.client,e.workspaceId,t.namespace)));return n.forEach((e,n)=>{t.set(e.namespace,o(r[n],`remote snapshot missing for "${e.namespace}"`))}),t}async function waitForCloneApplicationData(e,t){let n=t.pollInterval??1e3,i=t.timeout??3e5,a=Date.now()+i;for(;Date.now()<=a;){let i=await e.getCloneApplicationDataOperation({sourceWorkspaceId:t.sourceWorkspaceId,targetWorkspaceId:t.targetWorkspaceId,operationId:t.operationId});if(i.status===r.COMPLETED)return;if(i.status===r.FAILED)throw U({code:`MIGRATION_TEST_CLONE_FAILED`,message:`Application data clone failed: ${i.errorMessage||`unknown platform error`}`});if(i.status!==r.PENDING&&i.status!==r.PROCESSING)throw H(`Application data clone returned unexpected status ${i.status}.`);await delay(n)}throw U({code:`MIGRATION_TEST_CLONE_TIMEOUT`,message:`Application data clone timed out after ${Math.round(i/1e3)} seconds.`})}function loadSnapshotSeedData(e,t,n){let r={};for(let i of t){let t=n?.tables[i],a=K.join(e,`${i}.jsonl`),o;try{o=Y.readFileSync(a,`utf8`).trim()}catch(e){if(e.code===`ENOENT`){r[i]=[];continue}throw e}r[i]=o?o.split(`
86
+ `)};c.out(a)}catch(e){throw e instanceof Q&&e.code===Z.NotFound?U({code:`STATIC_WEBSITE_NOT_FOUND`,message:r,cause:e}):e}}});async function listStaticWebsites(e){let{client:t,workspaceId:n}=await D({profile:e?.profile,workspaceId:e?.workspaceId}),r=Ue(e?.order);return(await B(async(e,i)=>{let{staticwebsites:a,nextPageToken:o}=await t.listStaticWebsites({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e?.limit})).map(e=>({workspaceId:n,name:e.name,description:e.description,url:e.url,allowedIpAddresses:e.allowedIpAddresses}))}const ja=O({name:`list`,description:`List all static websites in a workspace.`,args:q.strictObject({...R,...Re()}),run:async e=>{let t=c.jsonMode,n=await listStaticWebsites({workspaceId:e[`workspace-id`],profile:e.profile,order:e.order,limit:e.limit}),r=t?n:n.map(({allowedIpAddresses:e,...t})=>{if(e.length===0)return{...t,allowedIpAddresses:`No allowed IP addresses`};let n=e.length,r=n===1?`1 IP address`:`${n} IP addresses`;return{...t,allowedIpAddresses:r}});c.out(r)}}),Ma=G({name:`staticwebsite`,description:`Manage static websites in your workspace.`,subCommands:{deploy:Xe,domain:ka,list:ja,get:Aa},async run(){await b(ja)}}),Na=new Set(Object.values(xt));async function activateBaseline(e,t,n,r){let i=await $.realpath(e),a=K.dirname(i),o=K.basename(i),s=await $.mkdtemp(K.join(a,`.${o}-rebaseline-`)),l=`${s}-previous`,u=!1,d=!1;try{await $.cp(i,s,{recursive:!0});for(let e of await $.readdir(s,{withFileTypes:!0})){if(!e.isDirectory()||!In.test(e.name))continue;let t=K.join(s,e.name);(await $.readdir(t)).some(e=>Na.has(e))&&await $.rm(t,{recursive:!0,force:!0})}let e={...t,namespace:n,version:6,createdAt:new Date().toISOString(),rebaseline:r},a=await et(e,s,0);g(a.filePath),await $.rename(i,l),u=!0;try{await $.rename(s,i),d=!0}catch(e){throw await $.rename(l,i),u=!1,e}try{await $.rm(l,{recursive:!0,force:!0})}catch(e){c.warn(`The previous migration directory remains at ${l}: ${e instanceof Error?e.message:String(e)}`)}u=!1}finally{Y.existsSync(s)&&await $.rm(s,{recursive:!0,force:!0}),!d&&u&&Y.existsSync(l)&&await $.rename(l,i)}}async function rebaseline(e){fe(`tailordb migration`);let{config:t,plugins:n}=await I(e.configPath),r=K.dirname(t.path),i=Vt(F(t,r),e.namespace),a=Tr({command:`tailor`,args:[`tailordb`,`migration`,`generate`,`--config`,t.path]});Dt(i.migrationsDir,i.namespace);let o=j(i.migrationsDir);if(!o)throw U({code:`MIGRATION_HISTORY_NOT_FOUND`,message:`No migration history found for namespace "${i.namespace}".`,suggestion:`Run ${a} first.`});let l=Nn(i.migrationsDir),u=j(i.migrationsDir,0)?.rebaseline?.historyId??null,d=an([i])[i.namespace],f=n.length>0?new Ir(n):void 0,{defineApplication:p}=await import(`../application-KZRJHv2j.mjs`),m=p({config:t,pluginManager:f});for(let e of m.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let h=m.tailorDBServices.find(e=>e.namespace===i.namespace);if(!h)throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${i.namespace}"`});let assertLocalTypesReady=()=>{let e=Yt(h.types,i.namespace),t=ge(o,e.tables,i.namespace);if(it(t))throw c.error(`Migration history does not reproduce the current local schema for namespace ${s.bold(i.namespace)}:`),c.log(Qe(t)),U({code:`MIGRATION_HISTORY_MISMATCH`,message:`Refusing to re-baseline: the migration history must reproduce the current local schema.`,suggestion:`Run ${a} first.`})},localSourceFiles=()=>[t.path,...yr(h.config,r)];assertLocalTypesReady();let g=gt(localSourceFiles()),{client:_,workspaceId:v}=await D({profile:e.profile,workspaceId:e.workspaceId}),b=[`--config`,t.path,...T({workspaceId:v,profile:e.profile})],x=Tr({command:`tailor`,args:[`tailordb`,`migration`,`set`,`0`,`--namespace`,i.namespace,...b]}),ee=Tr({command:`tailor`,args:[`deploy`,...b]}),assertConnectedWorkspaceReady=async(e,n)=>{let r=await xn(_,E(v,`tailordb`,i.namespace)),a=r.number;if(a!==l){let e=a===null?`<unset>`:y(a);throw U({code:`REBASELINE_CHECKPOINT_BEHIND`,message:`The connected workspace must be at the latest migration ${y(l)} before re-baselining; current checkpoint is ${e}.`})}if(r.historyIdInvalid)throw U({code:`REBASELINE_REMOTE_HISTORY_INVALID`,message:`Refusing to re-baseline: the connected workspace has an invalid migration history marker.`});if(r.historyId!==e)throw U(n===`confirmation`?{code:`REBASELINE_STATE_CHANGED`,message:`The connected workspace migration history changed while waiting for confirmation.`,suggestion:`Run the command again.`}:{code:`REBASELINE_REMOTE_HISTORY_MISMATCH`,message:`Refusing to re-baseline: the connected workspace does not match the local migration history.`});let o=await Ce(_,v,[i],t,[ue(h)]),s=o[0];if(!s||s.remoteMigrationNumber!==l||s.hasDrift||s.checkpointMissingLocal)throw s?.hasDrift&&(c.error(`Remote schema drift detected:`),c.log(pe(o))),U({code:`REBASELINE_REMOTE_SCHEMA_MISMATCH`,message:`Refusing to re-baseline: the connected workspace remote schema must match the latest migration.`})};if(await assertConnectedWorkspaceReady(u,`initial`),c.newline(),c.warn(`This will replace the migration history for ${s.bold(i.namespace)}.`),c.log(` Latest migration: ${y(l)}`),c.log(` New history: 0000/schema.json only`),c.log(` migrate.ts and db.ts files will disappear from the working tree.`),c.log(` Committed migration files will remain in Git history. Preserve any uncommitted files before continuing.`),c.log(` Every other environment must already be at the latest migration.`),c.log(` The connected workspace checkpoint will be reset to 0000.`),c.newline(),!e.yes&&!await k.confirm({message:`Re-baseline this migration history and reset the connected workspace checkpoint?`,default:!1})){c.info(`Operation cancelled.`);return}if(Dt(i.migrationsDir,i.namespace),an([i])[i.namespace]!==d)throw U({code:`REBASELINE_STATE_CHANGED`,message:`Migration files changed while waiting for confirmation.`,suggestion:`Run the command again.`});if(gt(localSourceFiles())!==g)throw U({code:`REBASELINE_STATE_CHANGED`,message:`Local TailorDB table or config files changed.`,suggestion:`Run the command again.`});assertLocalTypesReady(),await assertConnectedWorkspaceReady(u,`confirmation`);let S={historyId:Ne(),replacedHistoryId:u,replacedLatestMigration:l};await activateBaseline(i.migrationsDir,o,i.namespace,S);try{await ye(_,v,i.namespace,0,S.historyId)}catch(e){throw U({code:`REBASELINE_CHECKPOINT_UPDATE_FAILED`,message:`The local migration history was re-baselined, but the connected workspace checkpoint could not be updated.`,suggestion:`Run ${x}, or run ${ee} with schema checks enabled after resolving the connection error.`,cause:e})}c.success(`Re-baselined ${s.bold(i.namespace)} and reset the connected workspace checkpoint to 0000.`)}const Pa=O({name:`rebaseline`,description:`Collapse the full migration history into a new 0000 baseline.`,notes:`Re-baselining removes migrations after 0000 from the working tree, records a new migration history ID, and resets the connected workspace checkpoint without changing its schema or data. Every environment must already have applied the latest migration before you run this command.`,args:q.strictObject({...N,...C,namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await A({profile:e.profile}),await rebaseline({configPath:e.config,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile})}});async function set(e){fe(`tailordb migration`);let t=nt(e.number),{config:n}=await I(e.configPath),r=K.dirname(n.path),i=F(n,r),a=Vt(i,e.namespace),o=a.namespace;Dt(a.migrationsDir,o),ee(a.migrationsDir,t);let l=j(a.migrationsDir,0)?.rebaseline?.historyId,{client:u,workspaceId:d}=await D({profile:e.profile,workspaceId:e.workspaceId}),f=E(d,`tailordb`,o),p=await xn(u,f),m=p.number,h=m??0,g=p.historyIdInvalid?`<invalid>`:p.historyId??`<unset>`,_=l??`<unset>`;if(c.newline(),c.warn(`This operation will change TailorDB migration state metadata.`),c.log(`Namespace: ${s.bold(o)}`),c.log(`Current migration: ${m===null?`<unset>`:s.bold(y(m))}`),c.log(`New migration: ${s.bold(y(t))}`),c.log(`Current migration history ID: ${s.bold(g)}`),c.log(`New migration history ID: ${s.bold(_)}`),c.newline(),t<h?(c.warn(`Setting migration number backwards (${y(h)} → ${y(t)}) will cause previous migrations to be re-executed on next apply.`),c.newline()):t>h&&(c.warn(`Setting migration number forwards (${y(h)} → ${y(t)}) will skip migrations ${y(h+1)} to ${y(t)}.`),c.newline()),!e.yes){if(!await k.confirm({message:`Continue with migration checkpoint and history ID update?`,default:!1})){c.info(`Operation cancelled.`);return}c.newline()}await ot(u,{trn:f,labels:{[Ae]:le(t),...l?{[Ut]:l}:{}},remove:l?void 0:[Ut]}),c.success(`Migration checkpoint set to ${s.bold(y(t))} for namespace ${s.bold(o)}`)}const Fa=O({name:`set`,description:`Set migration checkpoint to a specific number.`,notes:"The migration number must be a 4-digit value (e.g. `0001`) or a bare integer (e.g. `1`) within 0–9999, and must exist in the local migration history; `0` is always accepted as the baseline, provided the local history passes validation. A gapped history is rejected.\n\nMetadata lookup failures (authentication, permission, or network errors) are reported as errors; only a not-yet-deployed namespace is treated as having no checkpoint.",args:q.strictObject({...N,...C,number:W(q.string(),{positional:!0,description:`Migration number to set (e.g., 0001 or 1)`}),namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await A({profile:e.profile}),await set({configPath:e.config,number:e.number,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile})}});function isStatusFailure(e){return e.status===`error`}async function collectMigrationStatuses(e){let{config:t}=await I(e.configPath),n=K.dirname(t.path),r=F(t,n);if(r.length===0)throw pn();let i=e.namespace?r.filter(t=>t.namespace===e.namespace):r;if(i.length===0)throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`Namespace "${e.namespace}" not found or does not have migrations configured`});let a=new Map,o=new Map;for(let{namespace:e,migrationsDir:t}of i)try{let n=ne(t),r=new Map,i=null;for(let e of n){if(e.type===`schema`){let t=g(e.path);e.number===0&&(i=t.rebaseline?.historyId??null);continue}try{let t=Kt(e.path);t.description&&r.set(e.number,t.description)}catch(e){if(Dr(e)&&e.code===`MIGRATION_FILE_VERSION_UNSUPPORTED`)throw e}}a.set(e,{migrationFiles:n,descriptions:r,historyId:i})}catch(t){o.set(e,Er(t))}if(a.size===0)return i.map(({namespace:e})=>({status:`error`,namespace:e,error:o.get(e)??`Failed to read local migration history.`}));let{client:s,workspaceId:c}=await D({profile:e.profile,workspaceId:e.workspaceId}),l=[];for(let{namespace:e}of i){if(o.has(e)){l.push({status:`error`,namespace:e,error:o.get(e)??`Failed to read local migration history.`});continue}let t=a.get(e);if(!t){l.push({status:`error`,namespace:e,error:`Failed to read local migration history.`});continue}let{migrationFiles:n,descriptions:r,historyId:i}=t,u=E(c,`tailordb`,e),d;try{d=await xn(s,u)}catch(t){l.push({status:`error`,namespace:e,error:t instanceof Error?t.message:String(t)});continue}let f=d.number??0;if(d.historyIdInvalid){l.push({status:`error`,namespace:e,error:`Remote migration history ID is invalid.`});continue}if((d.number!==null||d.historyId!==null)&&d.historyId!==i){l.push({status:`error`,namespace:e,error:`Remote migration history ID ${d.historyId??`<unset>`} does not match local migration history ID ${i??`<unset>`}.`});continue}let p=n.map(e=>e.number).filter((e,t,n)=>n.indexOf(e)===t).toSorted((e,t)=>e-t).filter(e=>e>f).map(e=>({number:e,label:y(e),...r.has(e)?{description:r.get(e)}:{}}));l.push({status:`ok`,namespace:e,currentMigration:f,currentMigrationLabel:y(f),pendingMigrations:p})}return l}function printMigrationStatuses(e){for(let t of e){if(c.newline(),c.info(`Namespace: ${s.bold(t.namespace)}`),isStatusFailure(t)){c.error(` Migration status error: ${t.error}`);continue}if(c.log(` Current migration: ${s.bold(t.currentMigrationLabel)}`),t.pendingMigrations.length>0){c.log(` Pending migrations:`);for(let e of t.pendingMigrations)e.description?c.log(` - ${e.label}: ${e.description}`):c.log(` - ${e.label}`)}else c.log(` Pending migrations: (none)`)}c.newline()}async function status(e){fe(`tailordb migration`);let t=await collectMigrationStatuses(e);e.json?c.out(t):printMigrationStatuses(t);let n=t.filter(isStatusFailure);if(n.length>0){let e=n.map(e=>e.namespace).join(`, `);throw U({code:`MIGRATION_STATUS_FAILED`,message:`Migration status check failed for ${n.length} namespace${n.length===1?``:`s`}: ${e}`})}}const Ia=O({name:`status`,description:`Show the current migration status for TailorDB namespaces, including applied and pending migrations.`,notes:`Every local migration file is checked for a compatible format version, and deployed migration history IDs must match the local baseline. Compatibility errors, history mismatches, and metadata lookup failures are reported per namespace and make the command exit non-zero; only a not-yet-deployed namespace is treated as having no applied migrations.`,args:q.strictObject({...N,namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (shows all namespaces if not specified)`})}),run:async e=>{await status({configPath:e.config,namespace:e.namespace,workspaceId:e[`workspace-id`],profile:e.profile,json:c.jsonMode})}});async function fetchRemoteGqlPermissions(e,t,n){return nr(async(r,i)=>{let{permissions:a,nextPageToken:o}=await e.listTailorDBGQLPermissions({workspaceId:t,namespaceName:n,pageToken:r,pageSize:i});return[a,o]})}async function fetchRemoteTypes(e,t,n){return er(async(r,i)=>{try{let{tailordbTypes:a,nextPageToken:o}=await e.listTailorDBTypes({workspaceId:t,namespaceName:n,pageToken:r,pageSize:i});return[a,o]}catch(e){throw e instanceof Q&&e.code===Z.NotFound?U({code:`MIGRATION_NAMESPACE_NOT_DEPLOYED`,message:`Cannot sync: TailorDB namespace "${n}" has not been deployed yet.`,suggestion:`Deploy the namespace before syncing its migration history.`,cause:e}):e}})}async function assertMigrationsReproduceLocalTypes(e,t){let{config:n,plugins:r}=e,i=r.length>0?new Ir(r):void 0,{defineApplication:a,generatePluginFilesIfNeeded:o}=await import(`../application-KZRJHv2j.mjs`),l=a({config:n,pluginManager:i}),u=l.tailorDBServices.find(e=>e.namespace===t.namespace);if(!u)throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${t.namespace}"`});for(let e of l.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let d=o(i,l.tailorDBServices,n.path),f=l.executorService??(d.length>0?(await import(`../service-BgrEteZ2.mjs`)).createExecutorService({config:{files:[]},baseDir:K.dirname(n.path)}):void 0);await f?.loadExecutors(),d.length>0&&await f?.loadPluginExecutorFiles([...d]);let p=new Set;for(let e of Object.values(f?.executors??{}))de(e)&&e.trigger.kind===`tailordb`&&p.add(e.trigger.tableName);let m={executorUsedTables:p,namespaceGqlOperations:u.config.gqlOperations},h=j(t.migrationsDir);if(!h)return m;let g=Yt(u.types,t.namespace),_=ge(h,g.tables,t.namespace);if(!it(_))return m;throw c.error(`Migration history does not reproduce the current local schema for namespace ${s.bold(t.namespace)}:`),c.log(Qe(_)),c.newline(),c.info(`This usually means one of the following:`),c.info(` - Migration files were edited and replaying them no longer matches the table definitions — fix the migration files.`,{mode:`plain`}),c.info(` - Table definitions changed without a new migration — run 'tailor tailordb migration generate' first.`,{mode:`plain`}),c.newline(),U({code:`MIGRATION_HISTORY_MISMATCH`,message:`Refusing to sync: the migration history must reproduce the current local schema before it can be applied to the remote.`,suggestion:`Generate a migration for the pending schema changes first.`})}async function sync(e){fe(`tailordb migration`);let t=nt(e.number),n=await I(e.configPath),{config:r}=n,i=K.dirname(r.path),a=F(r,i),o=Vt(a,e.namespace);Dt(o.migrationsDir,o.namespace);let l=ee(o.migrationsDir,t),u=j(o.migrationsDir,t);if(!u)throw U({code:`MIGRATION_BASELINE_NOT_FOUND`,message:`No initial schema snapshot found in ${o.migrationsDir}. Expected 0000/schema.json.`,suggestion:`Create the initial schema snapshot first.`});let f=await assertMigrationsReproduceLocalTypes(n,o),{client:p,workspaceId:m}=await D({profile:e.profile,workspaceId:e.workspaceId}),h=E(m,`tailordb`,o.namespace),g=await At(p,h),_=await fetchRemoteTypes(p,m,o.namespace),v=new Set(_.map(e=>e.name)),{creates:b,updates:x,deletes:S}=dt(u,v),te=await fetchRemoteGqlPermissions(p,m,o.namespace),C=new Set(te.map(e=>e.typeName)),w=Object.entries(u.tables).flatMap(([e,t])=>t.permissions?.gql?[{typeName:e,permission:d(t.permissions.gql)}]:[]),ne=new Set(w.map(e=>e.typeName)),re=te.filter(e=>!ne.has(e.typeName));if(c.newline(),c.info(`Namespace: ${s.bold(o.namespace)}`),c.log(` Current migration: ${g===null?`<unset>`:s.bold(y(g))}`),c.log(` Target migration: ${s.bold(y(t))}`),c.log(` Tables to create: ${s.bold(String(b.length))}`),c.log(` Tables to update: ${s.bold(String(x.length))}`),c.log(` Tables to delete: ${s.bold(String(S.length))}`),c.log(` GQL permissions to set: ${s.bold(String(w.length))}`),c.log(` GQL permissions to delete: ${s.bold(String(re.length))}`),c.newline(),b.length+x.length+S.length+w.length+re.length===0?c.info(`No tables to apply; only the migration label will be updated.`):(c.warn(`This operation will overwrite remote TailorDB tables to match the selected snapshot.`),S.length>0&&c.warn(`Existing data in deleted tables will be lost.`),c.newline()),c.warn(`Sync never runs migrate.ts scripts; it only applies the schema snapshot and moves the migration label.`),c.newline(),g!==null&&t<g?(c.warn(`Migrations ${y(t+1)}–${y(g)} will become pending again and re-execute on the next deploy, including their migrate.ts scripts. Make sure those scripts are idempotent (safe to re-run).`),c.newline()):g!==null&&t>g&&(c.warn(`Moving the migration label forwards (${y(g)} → ${y(t)}): migrate.ts scripts for migrations ${y(g+1)}–${y(t)} will not run on the next deploy.`),c.newline()),!e.yes){if(!await k.confirm({message:`Continue and set migration label to ${y(t)}?`,default:!1})){c.info(`Operation cancelled.`);return}c.newline()}let ie=Ve(u,f),manifestFor=e=>{let t=ie.get(e);if(!t)throw H(`Internal error: no manifest generated for table "${e}". No changes were applied.`);return t},ae=b.map(e=>manifestFor(e)),oe=x.map(e=>manifestFor(e));try{await Promise.all([...ae.map(e=>p.createTailorDBType({workspaceId:m,namespaceName:o.namespace,tailordbType:e})),...oe.map(e=>p.updateTailorDBType({workspaceId:m,namespaceName:o.namespace,tailordbType:e}))])}catch(e){ze(e,[`The target snapshot marks a field as required, but existing remote records have no value for it.`,`Populate those records first (e.g. with a migration script applied via 'tailor deploy'), then re-run the sync.`])}await Promise.all(w.map(({typeName:e,permission:t})=>{let n={workspaceId:m,namespaceName:o.namespace,typeName:e,permission:t};return C.has(e)?p.updateTailorDBGQLPermission(n):p.createTailorDBGQLPermission(n)})),await Promise.all(re.map(e=>p.deleteTailorDBGQLPermission({workspaceId:m,namespaceName:o.namespace,typeName:e.typeName}))),await Promise.all(S.map(e=>p.deleteTailorDBType({workspaceId:m,namespaceName:o.namespace,tailordbTypeName:e}))),await ot(p,{trn:h,labels:{[Ae]:le(t),...u.rebaseline?.historyId?{[Ut]:u.rebaseline.historyId}:{}},remove:u.rebaseline?.historyId?void 0:[Ut]}),c.success(`Synced namespace ${s.bold(o.namespace)} to migration ${s.bold(y(t))}.`),t<l&&(c.newline(),c.info(`Run 'tailor deploy' to apply migrations ${y(t+1)}–${y(l)} from the working tree.`))}const La=O({name:`sync`,description:`Sync remote TailorDB schema to a specific migration snapshot (recovery from --no-schema-check drift).`,args:q.strictObject({...N,...C,number:W(q.string(),{positional:!0,description:`Migration number to sync to (e.g., 0001 or 1; 0 targets the baseline snapshot)`}),namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await A({profile:e.profile}),await sync({configPath:e.config,number:e.number,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile})}});function delay(e){return e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve()}function assertSeedDataDirectory(e){let t;try{t=Y.statSync(e)}catch(t){throw t.code===`ENOENT`?U({code:`SEED_DATA_NOT_FOUND`,message:`Seed data directory not found: ${e}.`,suggestion:`Generate seed data before testing migrations.`,cause:t}):t}if(!t.isDirectory())throw U({code:`SEED_DATA_INVALID`,message:`Seed data path is not a directory: ${e}`})}function assertAssertionScript(e){let t=K.resolve(e),n;try{n=Y.statSync(t)}catch(e){throw e.code===`ENOENT`?U({code:`MIGRATION_ASSERTION_SCRIPT_NOT_FOUND`,message:`Migration assertion script not found: ${t}`,cause:e}):e}if(!n.isFile())throw U({code:`MIGRATION_ASSERTION_SCRIPT_INVALID`,message:`Migration assertion path is not a file: ${t}`})}function assertCloneTargetRegion(e,t){if(e!==t)throw U({code:`MIGRATION_TEST_REGION_MISMATCH`,message:`Clone mode requires source and target workspaces in the same region (source: ${e}, target: ${t}).`})}function assertTargetWorkspaceDiffers(e,t){if(t?.toLowerCase()===e.toLowerCase())throw U({code:`MIGRATION_TEST_TARGET_INVALID`,message:`The migration test target workspace must differ from the source workspace.`,command:`tailordb migration test`})}function resolveAssertionNamespace(e,t){let n=t??(e.length===1?e[0]:void 0);if(!n)throw U({code:`MIGRATION_TEST_ASSERT_NAMESPACE_REQUIRED`,message:`--assert-namespace is required when pending migrations span multiple namespaces.`,command:`tailordb migration test`});if(!e.includes(n))throw U({code:`MIGRATION_TEST_NO_PENDING_MIGRATIONS`,message:`Assertion namespace "${n}" has no pending migrations.`});return n}async function createMigrationTestBaselineSnapshots(e){let t=new Map([...e.baselines].map(([e,t])=>[e,t.snapshot]));if(e.dataMode!==`clone`)return t;let n=e.inputs.filter(e=>!t.has(e.namespace)),r=await Promise.all(n.map(t=>tt(e.client,e.workspaceId,t.namespace)));return n.forEach((e,n)=>{t.set(e.namespace,o(r[n],`remote snapshot missing for "${e.namespace}"`))}),t}async function waitForCloneApplicationData(e,t){let n=t.pollInterval??1e3,i=t.timeout??3e5,a=Date.now()+i;for(;Date.now()<=a;){let i=await e.getCloneApplicationDataOperation({sourceWorkspaceId:t.sourceWorkspaceId,targetWorkspaceId:t.targetWorkspaceId,operationId:t.operationId});if(i.status===r.COMPLETED)return;if(i.status===r.FAILED)throw U({code:`MIGRATION_TEST_CLONE_FAILED`,message:`Application data clone failed: ${i.errorMessage||`unknown platform error`}`});if(i.status!==r.PENDING&&i.status!==r.PROCESSING)throw H(`Application data clone returned unexpected status ${i.status}.`);await delay(n)}throw U({code:`MIGRATION_TEST_CLONE_TIMEOUT`,message:`Application data clone timed out after ${Math.round(i/1e3)} seconds.`})}function loadSnapshotSeedData(e,t,n){let r={};for(let i of t){let t=n?.tables[i],a=K.join(e,`${i}.jsonl`),o;try{o=Y.readFileSync(a,`utf8`).trim()}catch(e){if(e.code===`ENOENT`){r[i]=[];continue}throw e}r[i]=o?o.split(`
87
87
  `).map((e,n)=>{let r;try{r=JSON.parse(e)}catch(e){throw U({code:`SEED_DATA_INVALID`,message:`Invalid JSON in ${a} at line ${n+1}: ${e instanceof Error?e.message:String(e)}`,cause:e})}if(typeof r!=`object`||!r||Array.isArray(r))throw U({code:`SEED_DATA_INVALID`,message:`Invalid seed row in ${a} at line ${n+1}: expected a JSON object`});let i=r;return t?projectSeedObject(i,t.fields,new Set([`id`])):i}):[]}return r}function projectSeedObject(e,t,n=new Set){return Object.fromEntries(Object.entries(e).flatMap(([e,r])=>{let i=t[e];return i?[[e,projectSeedValue(r,i)]]:n.has(e)?[[e,r]]:[]}))}function projectSeedValue(e,t){let n=t.fields;return n?t.array?Array.isArray(e)?e.map(e=>isJsonObject(e)?projectSeedObject(e,n):e):e:isJsonObject(e)?projectSeedObject(e,n):e:e}function isJsonObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function sortSeedTypesForSnapshot(e){let t=Object.keys(e.tables),n=new Set(t),r=new Map,i=[];for(let[t,a]of Object.entries(e.tables)){let e=new Set;for(let r of Object.values(a.fields)){let a=r.foreignKeyType;a&&(a===t?i.push(t):n.has(a)&&e.add(a))}r.set(t,[...e])}let a=new Set,o=[],visit=e=>{if(!a.has(e)){a.add(e);for(let t of r.get(e)??[])visit(t);o.push(e)}};for(let e of t)visit(e);return{order:o,selfRefTypes:i}}function temporaryWorkspaceName(){return`migration-test-${new Date().toISOString().replace(/[-:T.Z]/g,``).slice(0,14)}-${ti(3).toString(`hex`)}`}function stateOrThrow(e){return o(e,`migration test runtime was used before preparation`)}async function assertSourceBaselineFresh(e,t,n){let r=e.loaded,i=F(r.config,K.dirname(r.config.path)),a=r.application.tailorDBServices.map(ue),o=(await Ce(e.client,n,i,r.config,a)).find(e=>e.hasDrift||e.checkpointMissingLocal||e.checkpointRepair);if(o)throw U({code:`MIGRATION_TEST_SOURCE_CHANGED`,message:`Source namespace "${o.namespace}" changed after migration test preparation.`,suggestion:`Run the migration test again.`});for(let r of i){let i=t.baselines.get(r.namespace);if(!i)continue;let a=await At(e.client,E(n,`tailordb`,r.namespace));if(a!==i.migrationNumber)throw U({code:`MIGRATION_TEST_SOURCE_CHANGED`,message:`Source namespace "${r.namespace}" moved from migration ${i.migrationNumber} to ${a??`none`} after migration test preparation.`,suggestion:`Run the migration test again.`})}let s=a.filter(e=>!t.baselines.has(e.namespace));for(let r of s){let i=t.baselineSnapshots.get(r.namespace);if(!i)continue;let a=await tt(e.client,n,r.namespace);if(Ee(i,a).changes.length>0)throw U({code:`MIGRATION_TEST_SOURCE_CHANGED`,message:`Source namespace "${r.namespace}" schema changed after migration test preparation.`,suggestion:`Run the migration test again.`})}}async function deleteExistingUserProfileConfig(e,t){let n=e.loaded.application.authService;if(!n)return;let r=n.config.name;await ir(()=>e.client.getUserProfileConfig({workspaceId:t,namespaceName:r}))&&await e.client.deleteUserProfileConfig({workspaceId:t,namespaceName:r})}function migrationConfig(e,t){return e.config.db?.[t]?.migration}function authExecutionContext(e,t,n){let r=e.loaded.application.authService;if(!r)throw U({code:`AUTH_CONFIG_REQUIRED`,message:`Auth configuration is required to execute migration test scripts.`});let i=n??ln(migrationConfig(e.loaded,t),r.config.machineUsers?Object.keys(r.config.machineUsers):void 0);if(!i)throw U({code:`MACHINE_USER_REQUIRED`,message:`No machine user is available for namespace "${t}".`,suggestion:`Pass --machine-user or configure one in auth or db.${t}.migration.`});return{authNamespace:r.config.name,machineUserName:i}}async function prepareMigrationTest(e){let t=await Ye({configPath:e.configPath}),n=K.dirname(t.config.path),r=F(t.config,n);if(r.length===0)throw pn();for(let e of r)Dt(e.migrationsDir,e.namespace);let i;e.data===`seed`&&(i=await je({configPath:t.config.path}),assertSeedDataDirectory(K.join(i.distPath,`data`))),e.assertionPath&&assertAssertionScript(e.assertionPath);let a=t.application.tailorDBServices.map(ue),s=await nn({profile:e.profile}),c=await Tt({profile:e.profile}),l=await cr(s,c),u=await on({workspaceId:e.workspaceId,profile:e.profile});assertTargetWorkspaceDiffers(u,e.targetWorkspaceId);let[d,f,p]=await Promise.all([l.getWorkspace({workspaceId:u}),l.getApplication({workspaceId:u,applicationName:t.config.name}),e.data===`clone`&&e.targetWorkspaceId?l.getWorkspace({workspaceId:e.targetWorkspaceId}):Promise.resolve(void 0)]),m=o(d.workspace,`source workspace "${u}" not found`);o(f.application,`application "${t.config.name}" not found in source workspace`);let h=p?o(p.workspace,`target workspace "${e.targetWorkspaceId}" not found`):void 0,g=await Ce(l,u,r,t.config,a),_=g.find(e=>e.hasDrift||e.checkpointMissingLocal);if(_)throw U({code:`MIGRATION_TEST_SOURCE_INVALID`,message:`Source namespace "${_.namespace}" does not match its migration checkpoint.`,suggestion:`Validate the migration history first.`});let v=g.find(e=>e.checkpointRepair);if(v)throw U({code:`MIGRATION_TEST_SOURCE_REPAIR_PENDING`,message:`Source namespace "${v.namespace}" has a pending migration checkpoint repair.`,suggestion:`Deploy to the source workspace first.`});let y=new Map,b=new Map,x=[];for(let e of r){let t=await At(l,E(u,`tailordb`,e.namespace));if(t===null)throw U({code:`MIGRATION_TEST_SOURCE_CHECKPOINT_MISSING`,message:`Source namespace "${e.namespace}" has no sdk-migration checkpoint.`,suggestion:`Deploy or set the migration checkpoint before testing.`});let n=Nn(e.migrationsDir);if(t>n)throw U({code:`MIGRATION_TEST_SOURCE_AHEAD`,message:`Source namespace "${e.namespace}" is at migration ${t}, but the local history ends at ${n}.`});let r=j(e.migrationsDir,t);if(!r)throw U({code:`MIGRATION_BASELINE_NOT_FOUND`,message:`No migration baseline snapshot found for namespace "${e.namespace}".`});y.set(e.namespace,{migrationNumber:t,snapshot:r,historyId:r.rebaseline?.historyId??null});let i=j(e.migrationsDir,n);if(!i)throw U({code:`MIGRATION_TEST_SNAPSHOT_NOT_FOUND`,message:`No target migration snapshot found for namespace "${e.namespace}".`});b.set(e.namespace,i),t<n&&x.push(e.namespace)}if(x.length===0)throw U({code:`MIGRATION_TEST_NO_PENDING_MIGRATIONS`,message:`No pending TailorDB migrations found in the source workspace.`});let ee=await createMigrationTestBaselineSnapshots({client:l,workspaceId:u,dataMode:e.data,inputs:a,baselines:y}),S={sourceWorkspaceId:u,sourceApplicationName:t.config.name,temporaryWorkspace:{name:temporaryWorkspaceName(),region:m.region,...m.organizationId?{organizationId:m.organizationId}:{},...m.folderId?{folderId:m.folderId}:{}},baselines:y,baselineSnapshots:ee,targetSnapshots:b,pendingNamespaces:x,...h?{designatedTarget:{id:h.id,region:h.region}}:{}};return{state:{client:l,loaded:t,options:e,...i?{seedContext:i}:{}},prepared:S}}function createMigrationTestDependencies(){let e;return{prepare:async t=>{let{state:n,prepared:r}=await prepareMigrationTest(t);return e=n,r},createWorkspace:async t=>{let n=stateOrThrow(e),r=await It(n.client,t.temporaryWorkspace);return c.info(`Created temporary workspace ${r.name} (${r.id}).`),{id:r.id,name:r.name}},deployBaseline:async({prepared:t,targetWorkspaceId:n})=>{let r=stateOrThrow(e);await deleteExistingUserProfileConfig(r,n),await Et({configPath:r.loaded.config.path,profile:r.options.profile,workspaceId:n,yes:!0},t.baselines,t.baselineSnapshots);for(let[e,i]of t.baselines)await ye(r.client,n,e,i.migrationNumber,i.historyId??void 0)},seedData:async({prepared:t,targetWorkspaceId:n})=>{let r=stateOrThrow(e),i=o(r.seedContext,`seed context missing after migration test preparation`),a=K.join(i.distPath,`data`);assertSeedDataDirectory(a);let s=new Map(r.loaded.application.tailorDBServices.map(e=>{let n=t.baselines.get(e.namespace),r=ue(e);return[e.namespace,n?.snapshot??z({version:1,namespace:e.namespace,createdAt:new Date().toISOString(),tables:r.types})]}));for(let[e,t]of s){let{order:o,selfRefTypes:s}=sortSeedTypesForSnapshot(t),c=loadSnapshotSeedData(a,o,t),l=o.filter(e=>(c[e]?.length??0)>0);if(l.length===0)continue;let u=await he(e,l,K.dirname(r.loaded.config.path)),d=Le({data:c,order:o,codeByteSize:new TextEncoder().encode(u.bundledCode).length}),f=authExecutionContext(r,e,r.options.machineUser??i.machineUserName);for(let t of d){let i=await qt({client:r.client,workspaceId:n,name:`migration-test-seed-${e}.ts`,code:u.bundledCode,arg:{data:t.data,order:t.order,selfRefTypes:s,upsert:!1},invoker:{namespace:f.authNamespace,machineUserName:f.machineUserName}});if(!i.success)throw U({code:`MIGRATION_TEST_SEED_FAILED`,message:i.error??`Seed execution failed for namespace "${e}".`});if(JSON.parse(i.result||`{}`).success!==!0)throw U({code:`MIGRATION_TEST_SEED_FAILED`,message:`Seed execution reported failure for namespace "${e}".`})}}},cloneData:async({prepared:t,sourceWorkspaceId:n,targetWorkspaceId:r,applicationName:i})=>{let a=stateOrThrow(e);await assertSourceBaselineFresh(a,t,n),c.warn(`Clone mode copies TailorDB records only; IdP users and file blobs are not copied.`);let o;try{o=(await a.client.cloneApplicationData({sourceWorkspaceId:n,sourceApplicationName:i,targetWorkspaceId:r,targetApplicationName:i})).operationId}catch(e){throw e instanceof Q&&e.code===Z.Unimplemented?U({code:`MIGRATION_TEST_CLONE_UNAVAILABLE`,message:`Application data clone is not enabled for this platform.`,suggestion:`Retry with --data seed.`,cause:e}):e}if(!o)throw H(`Application data clone returned no operation ID.`);await waitForCloneApplicationData(a.client,{sourceWorkspaceId:n,targetWorkspaceId:r,operationId:o})},deployMigrations:async({prepared:t,targetWorkspaceId:n})=>{let r=stateOrThrow(e);await Nt({configPath:r.loaded.config.path,profile:r.options.profile,workspaceId:n,yes:!0},t.targetSnapshots)},runAssertion:async({prepared:t,targetWorkspaceId:n,assertionPath:r,assertionNamespace:i,machineUser:a})=>{let o=stateOrThrow(e),s=resolveAssertionNamespace(t.pendingNamespaces,i),c=authExecutionContext(o,s,a),l=await at(r,s,0,o.loaded.config.env??{},K.dirname(o.loaded.config.path)),u=await qt({client:o.client,workspaceId:n,name:`migration-test-assert-${s}.ts`,code:l.bundledCode,invoker:{namespace:c.authNamespace,machineUserName:c.machineUserName}});if(!u.success)throw U({code:`MIGRATION_TEST_ASSERTION_FAILED`,message:u.error??`Migration assertion failed for namespace "${s}".`})},deleteWorkspace:async t=>{await stateOrThrow(e).client.deleteWorkspace({workspaceId:t})}}}async function runMigrationTest(e,t=createMigrationTestDependencies()){if(e.targetWorkspaceId&&!e.yes)throw U({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`--target-workspace-id requires --yes because the target may be overwritten.`,command:`tailordb migration test`});if(e.keep&&e.targetWorkspaceId)throw U({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`--keep applies only to automatically created workspaces; a designated target is always retained.`,command:`tailordb migration test`});if(e.assertionNamespace&&!e.assertionPath)throw U({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`--assert is required when --assert-namespace is provided.`,command:`tailordb migration test`});let n=await t.prepare(e);if(assertTargetWorkspaceDiffers(n.sourceWorkspaceId,e.targetWorkspaceId),e.assertionPath&&resolveAssertionNamespace(n.pendingNamespaces,e.assertionNamespace),e.data===`clone`&&e.targetWorkspaceId){let e=o(n.designatedTarget,`designated clone target was not loaded during preparation`);assertCloneTargetRegion(n.temporaryWorkspace.region,e.region)}let r=e.targetWorkspaceId===void 0,i=r?await t.createWorkspace(n):{id:o(e.targetWorkspaceId,`designated target workspace missing`),name:void 0},a,s=!1,l=!1;try{let r={prepared:n,targetWorkspaceId:i.id};await t.deployBaseline(r);let a={...r,sourceWorkspaceId:n.sourceWorkspaceId,applicationName:n.sourceApplicationName};e.data===`clone`?await t.cloneData(a):await t.seedData(a),await t.deployMigrations(r),e.assertionPath&&await t.runAssertion({...r,assertionPath:e.assertionPath,assertionNamespace:e.assertionNamespace,machineUser:e.machineUser})}catch(e){a=e,s=!0}if(r&&e.keep)c.info(`Keeping temporary workspace ${i.name??i.id}.`);else if(r)try{await t.deleteWorkspace(i.id),l=!0}catch(t){if(!s)throw U({code:`MIGRATION_TEST_WORKSPACE_CLEANUP_FAILED`,message:`Failed to delete temporary workspace ${i.id}: ${t instanceof Error?t.message:String(t)}`,suggestion:e.profile?`Delete the temporary workspace manually with TAILOR_PLATFORM_PROFILE=${e.profile}.`:`Delete the temporary workspace manually.`,next:{command:`tailor`,args:[`workspace`,`delete`,`--workspace-id`,i.id]},cause:t});c.warn(`Failed to delete temporary workspace ${i.id}: ${t instanceof Error?t.message:String(t)}`)}if(s)throw a;return{success:!0,workspaceId:i.id,...i.name?{workspaceName:i.name}:{},temporary:r,deleted:l,data:e.data,pendingNamespaces:n.pendingNamespaces}}async function migrationTest(e){fe(`tailordb migration`);let t=await runMigrationTest(e);if(e.json){c.out(t);return}c.success(`Pending migrations completed in workspace ${t.workspaceName??t.workspaceId}.`)}const Ra=O({name:`test`,description:`Test pending migrations with seed fixtures or cloned data in a temporary workspace.`,notes:`The source workspace is read-only. Without --target-workspace-id, the command creates a workspace in the source workspace's region and deletes it after success or failure; pass --keep to retain it for inspection. A designated target is retained and requires --yes. Clone mode copies TailorDB records only; it does not copy IdP users or file blobs.`,args:q.strictObject({...N,yes:W(q.boolean().default(!1),{alias:`y`,description:`Acknowledge that a designated target workspace may be overwritten`}),data:W(q.enum([`seed`,`clone`]).default(`seed`),{description:`Data source for the migration test (seed or clone)`}),"target-workspace-id":W(q.uuid().optional(),{description:`Existing throwaway workspace to retain after the test (requires --yes)`}),keep:W(q.boolean().default(!1),{description:`Keep the automatically created workspace after the test`}),assert:W(q.string().optional(),{description:`Path to a TypeScript assertion script to run after migrations`,completion:{type:`file`,extensions:[`ts`]}}),"assert-namespace":W(q.string().optional(),{description:`TailorDB namespace exposed to the assertion script`}),"machine-user":W(q.string().optional(),{description:`Machine user for seed and assertion script execution`})}),run:async e=>{await A({profile:e.profile}),await migrationTest({configPath:e.config,workspaceId:e[`workspace-id`],profile:e.profile,data:e.data,targetWorkspaceId:e[`target-workspace-id`],keep:e.keep,assertionPath:e.assert,assertionNamespace:e[`assert-namespace`],machineUser:e[`machine-user`],yes:e.yes,json:c.jsonMode})}});function assertMigrationScriptsReady(e,t,n){let r=[],i=[],a=[],o=[];for(let t of ne(e)){if(t.type!==`diff`)continue;let n=Kt(t.path),s=oe(e,t.number,`migrate`),c=Y.existsSync(s);n.requiresMigrationScript&&!n.scriptSkipped&&!c&&r.push(t.number),n.scriptSkipped&&c&&i.push(t.number),c&&Y.readFileSync(s,`utf8`).includes(`TODO(tailor-migration-review)`)&&a.push(t.number),n.hasWarnings&&!n.scriptSkipped&&!c&&o.push({migrationNumber:t.number,warnings:n.warnings})}if(r.length>0)throw U({code:`MIGRATION_SCRIPT_REQUIRED`,message:`Migration(s) ${r.map(y).join(`, `)} in namespace "${t}" require a migration script but have no migrate.ts.`,suggestion:`Add one with 'tailor tailordb migration script <number>', or record that no script is needed with 'tailor tailordb migration script <number> --no-script --reason "..."'.`});if(i.length>0){let e=i.map(e=>` ${lt({migrationNumber:e,namespace:t,configPath:n})}`).join(`
88
- `);throw U({code:`MIGRATION_SCRIPT_SKIP_CONFLICT`,message:`Migration(s) ${i.map(y).join(`, `)} in namespace "${t}" have both a --no-script skip acknowledgment and migrate.ts.`,suggestion:`Clear the stale acknowledgment(s):\n${e}\nOr delete migrate.ts to keep the skip.`})}if(a.length>0)throw U({code:`MIGRATION_SCRIPT_REVIEW_REQUIRED`,message:`Migration(s) ${a.map(y).join(`, `)} in namespace "${t}" contain generated normalization logic that still requires review in migrate.ts.`,suggestion:`Review each ${_} marker, then remove the marker and its associated \`never\` annotation.`});return o}function buildValidationReports(e){let{targetNamespaces:t,migrationFileErrors:n,localResults:r,remoteResults:i,unacknowledgedWarnings:a}=e;return t.map(e=>{let t=n.get(e.namespace);if(t!==void 0)return{namespace:e.namespace,valid:!1,migrationFiles:{valid:!1,error:t}};let s=o(r.find(t=>t.namespace===e.namespace),`local schema check result missing for namespace "${e.namespace}"`),c={hasDiff:s.hasDiff,...s.diff?{diff:s.diff}:{}};if(i===void 0)return{namespace:e.namespace,valid:!1,migrationFiles:{valid:!0},localSchema:c,remoteSchema:{skipped:`check_failed`}};let l=o(i.find(t=>t.namespace===e.namespace),`remote schema check result missing for namespace "${e.namespace}"`),u=l.checkpointMissingLocal===!0,d={remoteMigrationNumber:l.remoteMigrationNumber,hasDrift:l.hasDrift,drifts:l.drifts,...l.skipped?{skipped:l.skipped}:{},...u?{checkpointMissingLocal:!0}:{},...l.rebaselinePending?{rebaselinePending:l.rebaselinePending}:{},...l.checkpointRepair?{checkpointRepair:l.checkpointRepair}:{}},f=a?.get(e.namespace),p;if(f!==void 0){let e=f.filter(e=>e.migrationNumber>l.remoteMigrationNumber);p={valid:e.length===0,missing:e}}return{namespace:e.namespace,valid:!c.hasDiff&&!d.hasDrift&&!u&&p?.valid!==!1,migrationFiles:{valid:!0},localSchema:c,remoteSchema:d,...p?{warningAcknowledgments:p}:{}}})}async function collectValidationReports(e){let{config:t,plugins:n}=await I(e.configPath),r=K.dirname(t.path),i=F(t,r);if(i.length===0)throw pn();let a=e.namespace?i.filter(t=>t.namespace===e.namespace):i;if(a.length===0)throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`Namespace "${e.namespace}" not found or does not have migrations configured`});let o=n.length>0?new Ir(n):void 0,{defineApplication:s}=await import(`../application-Dl94fzpm.mjs`),c=s({config:t,pluginManager:o});for(let e of c.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();vr({tailorDBServices:c.tailorDBServices});for(let{namespace:e}of a)if(!c.tailorDBServices.some(t=>t.namespace===e))throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${e}"`});let l=c.tailorDBServices.map(ue),u=new Map(l.map(e=>[e.namespace,e.types])),d=new Map,f=[],p=e.strict?new Map:void 0;for(let t of a)try{Dt(t.migrationsDir,t.namespace),j(t.migrationsDir);let n=assertMigrationScriptsReady(t.migrationsDir,t.namespace,e.configPath);p?.set(t.namespace,n),f.push(t)}catch(e){d.set(t.namespace,Er(e))}let m={targetNamespaces:a,migrationFileErrors:d,localResults:await v(u,f),...p?{unacknowledgedWarnings:p}:{}};if(f.length===0)return{reports:buildValidationReports(m)};let h;try{let{client:n,workspaceId:r}=await D({profile:e.profile,workspaceId:e.workspaceId});h=await Ce(n,r,f,t,l)}catch(e){return{reports:buildValidationReports(m),remoteError:e}}return{reports:buildValidationReports({...m,remoteResults:h})}}function printValidationReports(e){for(let t of e){if(c.newline(),c.info(`Namespace: ${s.bold(t.namespace)}`),!t.migrationFiles.valid){c.log(` Migration files: ${s.error(`invalid`)}`),c.log(` ${t.migrationFiles.error}`);continue}c.log(` Migration files: ${s.success(`OK`)}`);let e=t.localSchema;e?.hasDiff?e.diff?(c.log(` Local schema: ${s.error(`changes not in migration files`)}`),c.log(` ${me(e.diff)}`),c.log(Qe(e.diff))):c.log(` Local schema: ${s.error(`no migration snapshot found`)}`):c.log(` Local schema: ${s.success(`OK`)}`);let n=t.remoteSchema;n?.skipped===`check_failed`?c.log(` Remote schema: ${s.error(`not checked`)}`):n?.checkpointRepair?c.log(` Remote schema: ${s.success(`OK`)} (next deploy will reset the checkpoint to 0000 from ${y(n.checkpointRepair.from)})`):n?.checkpointMissingLocal?(c.log(` Remote schema: ${s.error(`remote migration ${y(n.remoteMigrationNumber)} is not in the local migration history`)}`),n.rebaselinePending&&c.log(` Fell behind before 'migration rebaseline' ran; must reach ${y(n.rebaselinePending.replacedLatestMigration)} first.`)):n?.hasDrift?(c.log(` Remote schema: ${s.error(`drift detected`)} (remote migration: ${y(n.remoteMigrationNumber)})`),c.log(wt(n.drifts))):n?.skipped===`not_deployed`?c.log(` Remote schema: ${s.dim(`skipped (namespace not deployed)`)}`):n?.skipped===`no_migration_label`?c.log(` Remote schema: ${s.dim(`skipped (deployed namespace has no migration state)`)}`):n?.skipped===`no_snapshot`?c.log(` Remote schema: ${s.dim(`skipped (no local snapshot for remote migration ${y(n.remoteMigrationNumber)})`)}`):n&&c.log(` Remote schema: ${s.success(`OK`)} (remote migration: ${y(n.remoteMigrationNumber)})`);let r=t.warningAcknowledgments;if(r){if(r.valid)c.log(` Warning acknowledgments: ${s.success(`OK`)}`);else{c.log(` Warning acknowledgments: ${s.error(`missing for pending migration(s) with possible data loss`)}`);for(let e of r.missing){let t=y(e.migrationNumber);for(let n of e.warnings){let e=n.fieldName?`.${n.fieldName}`:``;c.log(` ${t}: ${n.tableName}${e}: ${n.reason}`)}}}}}c.newline()}function hasMissingCheckpoint(e){return e.remoteSchema?.checkpointMissingLocal===!0}function printResolutionHints(e,t){e.some(e=>e.localSchema?.hasDiff&&!e.localSchema.diff)&&c.info(`Run 'tailor tailordb migration generate' to create the initial snapshot.`),e.some(e=>e.localSchema?.diff)&&c.info(`Run 'tailor tailordb migration generate' to create migration files.`);let n=e.filter(hasMissingCheckpoint);n.length>0&&Ze(n.map(e=>({namespace:e.namespace,remoteMigrationNumber:e.remoteSchema.remoteMigrationNumber,...e.remoteSchema.rebaselinePending?{rebaselinePending:e.remoteSchema.rebaselinePending}:{}}))),e.some(e=>e.remoteSchema?.hasDrift)&&rt(e.map(e=>({hasDrift:e.remoteSchema?.hasDrift??!1,drifts:e.remoteSchema?.drifts??[]})));let r=e.filter(e=>e.warningAcknowledgments&&!e.warningAcknowledgments.valid);if(r.length>0){c.info(`For each migration listed, either add a data migration script with 'tailor tailordb migration script <number>' or record why none is needed:`);for(let e of r)for(let n of e.warningAcknowledgments?.missing??[])c.info(` ${lt({migrationNumber:n.migrationNumber,namespace:e.namespace,configPath:t,noScript:!0})}`,{mode:`plain`})}}async function validate(e){fe(`tailordb migration`);let t=await collectValidationReports(e),{reports:n}=t,r=n.filter(e=>!e.valid).length;if(e.json?c.out(n):(printValidationReports(n),r===0&&!(`remoteError`in t)?c.success(`All migration validation checks passed.`):printResolutionHints(n,e.configPath)),`remoteError`in t)throw t.remoteError;if(r>0)throw U({code:`MIGRATION_VALIDATION_FAILED`,message:`Migration validation failed for ${r} namespace(s)`})}const za=O({name:`validate`,description:`Validate the full migration history, unreviewed generated migration scripts, and schema drift (local tables vs. migration snapshot, remote schema vs. migration checkpoint) without deploying. This includes the migration and schema-drift checks used by 'deploy' and exits with a non-zero code when issues are found.`,args:q.strictObject({...N,namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (validates all namespaces if not specified)`}),strict:W(q.boolean().default(!1),{description:`Also fail when a pending migration can drop data without an acknowledgment`})}),run:async e=>{await validate({configPath:e.config,namespace:e.namespace,workspaceId:e[`workspace-id`],profile:e.profile,json:c.jsonMode,strict:e.strict})}}),Ba=G({name:`migration`,description:`Manage TailorDB schema migrations.`,subCommands:{generate:He,rebaseline:Pa,script:Vn,set:Fa,status:Ia,sync:La,test:Ra,validate:za}}),Va=G({name:`tailordb`,description:`Manage TailorDB tables and data.`,notes:"The `tailordb erd` commands are provided by the @tailor-platform/sdk-plugin-tailordb-erd CLI plugin.",subCommands:{truncate:Oe,migration:Ba}}),Ha=O({name:`upgrade`,description:`Run codemods to upgrade your project to a newer SDK version.`,args:q.strictObject({from:W(q.string(),{description:`SDK version before the upgrade (e.g., 1.33.0)`}),"dry-run":W(q.boolean().default(!1),{alias:`d`,description:`Preview changes without modifying files`}),path:W(q.string().default(`.`),{description:`Project directory to upgrade`,completion:{type:`directory`}})}),run:async e=>{let{initTelemetry:t}=await import(`../telemetry-DXHP3VVi.mjs`);await t();let{upgrade:n}=await import(`../service-B4Gh_bbL.mjs`);await n({from:e.from,dryRun:e[`dry-run`],path:K.resolve(e.path)})}}),Ua=O({name:`current`,description:`Show current user.`,args:q.strictObject({profile:R.profile}),run:async e=>{let t=await M(),n=e.profile||process.env.TAILOR_PLATFORM_PROFILE,r=n?t.profiles[n]:void 0;if(n&&!r)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${n}" not found`});let i=r?P(r):void 0,a=n?r?.user??null:t.current_user,o=c.jsonMode;if(!a)throw U({code:`USER_NOT_SET`,message:`Current user not set.`,suggestion:`Log in first to register a user.`,next:{command:`tailor`,args:[`login`,...T({profile:n})]}});if(!mt(t,a,i))throw U({code:`USER_NOT_FOUND`,message:`Current user '${a}' not found in registered users.`,suggestion:`Log in again to register the user.`,next:{command:`tailor`,args:[`login`,...T({profile:n})]}});if(o){c.out({user:a});return}c.out(a)}});function activeCurrentUserKey(e,t){if(!t)return e.current_user?Rn(e,e.current_user):null;let n=e.profiles[t];if(!n)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${t}" not found`});return Rn(e,n.user,P(n))}function toUserListInfo(e,t){let n=e.indexOf(`|`),r=n===-1?null:e.slice(0,n);return{user:n===-1?e:e.slice(n+1),platformUrl:r,current:t===e}}function formatUserListInfo(e){return`${e.user}${e.platformUrl?` [${e.platformUrl}]`:``}${e.current?` (current)`:``}`}const Wa=O({name:`list`,description:`List all users.`,args:q.strictObject({profile:R.profile}),run:async e=>{let t=await M(),n=c.jsonMode,r=activeCurrentUserKey(t,e.profile||process.env.TAILOR_PLATFORM_PROFILE),i=Object.keys(t.users);if(i.length===0){c.info(V`
88
+ `);throw U({code:`MIGRATION_SCRIPT_SKIP_CONFLICT`,message:`Migration(s) ${i.map(y).join(`, `)} in namespace "${t}" have both a --no-script skip acknowledgment and migrate.ts.`,suggestion:`Clear the stale acknowledgment(s):\n${e}\nOr delete migrate.ts to keep the skip.`})}if(a.length>0)throw U({code:`MIGRATION_SCRIPT_REVIEW_REQUIRED`,message:`Migration(s) ${a.map(y).join(`, `)} in namespace "${t}" contain generated normalization logic that still requires review in migrate.ts.`,suggestion:`Review each ${_} marker, then remove the marker and its associated \`never\` annotation.`});return o}function buildValidationReports(e){let{targetNamespaces:t,migrationFileErrors:n,localResults:r,remoteResults:i,unacknowledgedWarnings:a}=e;return t.map(e=>{let t=n.get(e.namespace);if(t!==void 0)return{namespace:e.namespace,valid:!1,migrationFiles:{valid:!1,error:t}};let s=o(r.find(t=>t.namespace===e.namespace),`local schema check result missing for namespace "${e.namespace}"`),c={hasDiff:s.hasDiff,...s.diff?{diff:s.diff}:{}};if(i===void 0)return{namespace:e.namespace,valid:!1,migrationFiles:{valid:!0},localSchema:c,remoteSchema:{skipped:`check_failed`}};let l=o(i.find(t=>t.namespace===e.namespace),`remote schema check result missing for namespace "${e.namespace}"`),u=l.checkpointMissingLocal===!0,d={remoteMigrationNumber:l.remoteMigrationNumber,hasDrift:l.hasDrift,drifts:l.drifts,...l.skipped?{skipped:l.skipped}:{},...u?{checkpointMissingLocal:!0}:{},...l.rebaselinePending?{rebaselinePending:l.rebaselinePending}:{},...l.checkpointRepair?{checkpointRepair:l.checkpointRepair}:{}},f=a?.get(e.namespace),p;if(f!==void 0){let e=f.filter(e=>e.migrationNumber>l.remoteMigrationNumber);p={valid:e.length===0,missing:e}}return{namespace:e.namespace,valid:!c.hasDiff&&!d.hasDrift&&!u&&p?.valid!==!1,migrationFiles:{valid:!0},localSchema:c,remoteSchema:d,...p?{warningAcknowledgments:p}:{}}})}async function collectValidationReports(e){let{config:t,plugins:n}=await I(e.configPath),r=K.dirname(t.path),i=F(t,r);if(i.length===0)throw pn();let a=e.namespace?i.filter(t=>t.namespace===e.namespace):i;if(a.length===0)throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`Namespace "${e.namespace}" not found or does not have migrations configured`});let o=n.length>0?new Ir(n):void 0,{defineApplication:s}=await import(`../application-KZRJHv2j.mjs`),c=s({config:t,pluginManager:o});for(let e of c.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();vr({tailorDBServices:c.tailorDBServices});for(let{namespace:e}of a)if(!c.tailorDBServices.some(t=>t.namespace===e))throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${e}"`});let l=c.tailorDBServices.map(ue),u=new Map(l.map(e=>[e.namespace,e.types])),d=new Map,f=[],p=e.strict?new Map:void 0;for(let t of a)try{Dt(t.migrationsDir,t.namespace),j(t.migrationsDir);let n=assertMigrationScriptsReady(t.migrationsDir,t.namespace,e.configPath);p?.set(t.namespace,n),f.push(t)}catch(e){d.set(t.namespace,Er(e))}let m={targetNamespaces:a,migrationFileErrors:d,localResults:await v(u,f),...p?{unacknowledgedWarnings:p}:{}};if(f.length===0)return{reports:buildValidationReports(m)};let h;try{let{client:n,workspaceId:r}=await D({profile:e.profile,workspaceId:e.workspaceId});h=await Ce(n,r,f,t,l)}catch(e){return{reports:buildValidationReports(m),remoteError:e}}return{reports:buildValidationReports({...m,remoteResults:h})}}function printValidationReports(e){for(let t of e){if(c.newline(),c.info(`Namespace: ${s.bold(t.namespace)}`),!t.migrationFiles.valid){c.log(` Migration files: ${s.error(`invalid`)}`),c.log(` ${t.migrationFiles.error}`);continue}c.log(` Migration files: ${s.success(`OK`)}`);let e=t.localSchema;e?.hasDiff?e.diff?(c.log(` Local schema: ${s.error(`changes not in migration files`)}`),c.log(` ${me(e.diff)}`),c.log(Qe(e.diff))):c.log(` Local schema: ${s.error(`no migration snapshot found`)}`):c.log(` Local schema: ${s.success(`OK`)}`);let n=t.remoteSchema;n?.skipped===`check_failed`?c.log(` Remote schema: ${s.error(`not checked`)}`):n?.checkpointRepair?c.log(` Remote schema: ${s.success(`OK`)} (next deploy will reset the checkpoint to 0000 from ${y(n.checkpointRepair.from)})`):n?.checkpointMissingLocal?(c.log(` Remote schema: ${s.error(`remote migration ${y(n.remoteMigrationNumber)} is not in the local migration history`)}`),n.rebaselinePending&&c.log(` Fell behind before 'migration rebaseline' ran; must reach ${y(n.rebaselinePending.replacedLatestMigration)} first.`)):n?.hasDrift?(c.log(` Remote schema: ${s.error(`drift detected`)} (remote migration: ${y(n.remoteMigrationNumber)})`),c.log(wt(n.drifts))):n?.skipped===`not_deployed`?c.log(` Remote schema: ${s.dim(`skipped (namespace not deployed)`)}`):n?.skipped===`no_migration_label`?c.log(` Remote schema: ${s.dim(`skipped (deployed namespace has no migration state)`)}`):n?.skipped===`no_snapshot`?c.log(` Remote schema: ${s.dim(`skipped (no local snapshot for remote migration ${y(n.remoteMigrationNumber)})`)}`):n&&c.log(` Remote schema: ${s.success(`OK`)} (remote migration: ${y(n.remoteMigrationNumber)})`);let r=t.warningAcknowledgments;if(r){if(r.valid)c.log(` Warning acknowledgments: ${s.success(`OK`)}`);else{c.log(` Warning acknowledgments: ${s.error(`missing for pending migration(s) with possible data loss`)}`);for(let e of r.missing){let t=y(e.migrationNumber);for(let n of e.warnings){let e=n.fieldName?`.${n.fieldName}`:``;c.log(` ${t}: ${n.tableName}${e}: ${n.reason}`)}}}}}c.newline()}function hasMissingCheckpoint(e){return e.remoteSchema?.checkpointMissingLocal===!0}function printResolutionHints(e,t){e.some(e=>e.localSchema?.hasDiff&&!e.localSchema.diff)&&c.info(`Run 'tailor tailordb migration generate' to create the initial snapshot.`),e.some(e=>e.localSchema?.diff)&&c.info(`Run 'tailor tailordb migration generate' to create migration files.`);let n=e.filter(hasMissingCheckpoint);n.length>0&&Ze(n.map(e=>({namespace:e.namespace,remoteMigrationNumber:e.remoteSchema.remoteMigrationNumber,...e.remoteSchema.rebaselinePending?{rebaselinePending:e.remoteSchema.rebaselinePending}:{}}))),e.some(e=>e.remoteSchema?.hasDrift)&&rt(e.map(e=>({hasDrift:e.remoteSchema?.hasDrift??!1,drifts:e.remoteSchema?.drifts??[]})));let r=e.filter(e=>e.warningAcknowledgments&&!e.warningAcknowledgments.valid);if(r.length>0){c.info(`For each migration listed, either add a data migration script with 'tailor tailordb migration script <number>' or record why none is needed:`);for(let e of r)for(let n of e.warningAcknowledgments?.missing??[])c.info(` ${lt({migrationNumber:n.migrationNumber,namespace:e.namespace,configPath:t,noScript:!0})}`,{mode:`plain`})}}async function validate(e){fe(`tailordb migration`);let t=await collectValidationReports(e),{reports:n}=t,r=n.filter(e=>!e.valid).length;if(e.json?c.out(n):(printValidationReports(n),r===0&&!(`remoteError`in t)?c.success(`All migration validation checks passed.`):printResolutionHints(n,e.configPath)),`remoteError`in t)throw t.remoteError;if(r>0)throw U({code:`MIGRATION_VALIDATION_FAILED`,message:`Migration validation failed for ${r} namespace(s)`})}const za=O({name:`validate`,description:`Validate the full migration history, unreviewed generated migration scripts, and schema drift (local tables vs. migration snapshot, remote schema vs. migration checkpoint) without deploying. This includes the migration and schema-drift checks used by 'deploy' and exits with a non-zero code when issues are found.`,args:q.strictObject({...N,namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (validates all namespaces if not specified)`}),strict:W(q.boolean().default(!1),{description:`Also fail when a pending migration can drop data without an acknowledgment`})}),run:async e=>{await validate({configPath:e.config,namespace:e.namespace,workspaceId:e[`workspace-id`],profile:e.profile,json:c.jsonMode,strict:e.strict})}}),Ba=G({name:`migration`,description:`Manage TailorDB schema migrations.`,subCommands:{generate:He,rebaseline:Pa,script:Vn,set:Fa,status:Ia,sync:La,test:Ra,validate:za}}),Va=G({name:`tailordb`,description:`Manage TailorDB tables and data.`,notes:"The `tailordb erd` commands are provided by the @tailor-platform/sdk-plugin-tailordb-erd CLI plugin.",subCommands:{truncate:Oe,migration:Ba}}),Ha=O({name:`upgrade`,description:`Run codemods to upgrade your project to a newer SDK version.`,args:q.strictObject({from:W(q.string(),{description:`SDK version before the upgrade (e.g., 1.33.0)`}),"dry-run":W(q.boolean().default(!1),{alias:`d`,description:`Preview changes without modifying files`}),path:W(q.string().default(`.`),{description:`Project directory to upgrade`,completion:{type:`directory`}})}),run:async e=>{let{initTelemetry:t}=await import(`../telemetry-DXHP3VVi.mjs`);await t();let{upgrade:n}=await import(`../service-B4Gh_bbL.mjs`);await n({from:e.from,dryRun:e[`dry-run`],path:K.resolve(e.path)})}}),Ua=O({name:`current`,description:`Show current user.`,args:q.strictObject({profile:R.profile}),run:async e=>{let t=await M(),n=e.profile||process.env.TAILOR_PLATFORM_PROFILE,r=n?t.profiles[n]:void 0;if(n&&!r)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${n}" not found`});let i=r?P(r):void 0,a=n?r?.user??null:t.current_user,o=c.jsonMode;if(!a)throw U({code:`USER_NOT_SET`,message:`Current user not set.`,suggestion:`Log in first to register a user.`,next:{command:`tailor`,args:[`login`,...T({profile:n})]}});if(!mt(t,a,i))throw U({code:`USER_NOT_FOUND`,message:`Current user '${a}' not found in registered users.`,suggestion:`Log in again to register the user.`,next:{command:`tailor`,args:[`login`,...T({profile:n})]}});if(o){c.out({user:a});return}c.out(a)}});function activeCurrentUserKey(e,t){if(!t)return e.current_user?Rn(e,e.current_user):null;let n=e.profiles[t];if(!n)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${t}" not found`});return Rn(e,n.user,P(n))}function toUserListInfo(e,t){let n=e.indexOf(`|`),r=n===-1?null:e.slice(0,n);return{user:n===-1?e:e.slice(n+1),platformUrl:r,current:t===e}}function formatUserListInfo(e){return`${e.user}${e.platformUrl?` [${e.platformUrl}]`:``}${e.current?` (current)`:``}`}const Wa=O({name:`list`,description:`List all users.`,args:q.strictObject({profile:R.profile}),run:async e=>{let t=await M(),n=c.jsonMode,r=activeCurrentUserKey(t,e.profile||process.env.TAILOR_PLATFORM_PROFILE),i=Object.keys(t.users);if(i.length===0){c.info(V`
89
89
  No users found.
90
90
  Please login first using 'tailor login' command to register a user.
91
91
  `),n&&c.out([]);return}let a=i.map(e=>toUserListInfo(e,r));if(n){c.out([...new Set(a.map(e=>e.user))]);return}a.forEach(e=>{e.current?c.success(formatUserListInfo(e),{mode:`plain`}):c.log(formatUserListInfo(e))})}});function patScopeToString(e){switch(e){case n.PAT_SCOPE_READ:return`read`;case n.PAT_SCOPE_WRITE:return`write`;default:return`unknown`}}function transformPersonalAccessToken(e){return{name:e.name,scopes:e.scopes.map(patScopeToString),createdAt:Ge(e.createdAt),lastUsedAt:Ge(e.lastUsedAt)}}function getScopesFromWriteFlag(e){return e?[n.PAT_SCOPE_READ,n.PAT_SCOPE_WRITE]:[n.PAT_SCOPE_READ]}function getScopeStringsFromWriteFlag(e){return e?[`read`,`write`]:[`read`]}function printCreatedToken(e,t,n,r){let i=getScopeStringsFromWriteFlag(n);c.jsonMode?c.out({name:e,scopes:i,token:t}):c.out(V`
@@ -1 +1,2 @@
1
+ import "../../../types/executor.generated.mjs";
1
2
  import "../../../configure/config/types.mjs";
@@ -1,5 +1,5 @@
1
1
  # politty-completion-version: 1
2
- # politty-bin-sig: 1789613465
2
+ # politty-bin-sig: 1789638132
3
3
  # politty-bin-path: /home/runner/work/sdk/sdk/node_modules/.bin/tailor
4
4
  # program: tailor
5
5
  # shell: zsh
@@ -1,4 +1,4 @@
1
- import { DateFieldOptions, DateFieldValue, FieldMetadata, FieldOptions, FieldOutput, TailorFieldType } from "./types/field.types.mjs";
1
+ import { DateFieldOptions, DateFieldValue, DateTimeFieldOptions, DateTimeFieldValue, FieldMetadata, FieldOptions, FieldOutput, TailorFieldType, TimeFieldOptions, TimeFieldValue } from "./types/field.types.mjs";
2
2
  import { AttributeList, Attributes, Env, TailorPrincipal } from "../runtime/types.mjs";
3
3
  import { DeepWritable, NullableToOptional, helpers_d_exports, output as output$1 } from "../types/helpers.mjs";
4
4
  import { IsAutoFilledDBField, IsReadOnlyDBField, PluginAttachment } from "./services/tailordb/types.mjs";
@@ -123,26 +123,26 @@ export declare const t: {
123
123
  }] ? DateFieldValue<Opt["as"]>[] : DateFieldValue<Opt["as"]>) | null : [Opt] extends [{
124
124
  array: true;
125
125
  }] ? DateFieldValue<Opt["as"]>[] : DateFieldValue<Opt["as"]>, FieldMetadata, TailorFieldType>;
126
- datetime: <const Opt extends FieldOptions>(options?: Opt) => import("@tailor-platform/sdk").TailorField<{
126
+ datetime: <const Opt extends DateTimeFieldOptions = FieldOptions>(options?: Opt) => import("@tailor-platform/sdk").TailorField<{
127
127
  type: "datetime";
128
128
  array: Opt extends {
129
129
  array: true;
130
130
  } ? true : false;
131
131
  }, Opt["optional"] extends true ? ([Opt] extends [{
132
132
  array: true;
133
- }] ? (string | Date)[] : string | Date) | null : [Opt] extends [{
133
+ }] ? DateTimeFieldValue<Opt["as"]>[] : DateTimeFieldValue<Opt["as"]>) | null : [Opt] extends [{
134
134
  array: true;
135
- }] ? (string | Date)[] : string | Date, FieldMetadata, TailorFieldType>;
136
- time: <const Opt extends FieldOptions>(options?: Opt) => import("@tailor-platform/sdk").TailorField<{
135
+ }] ? DateTimeFieldValue<Opt["as"]>[] : DateTimeFieldValue<Opt["as"]>, FieldMetadata, TailorFieldType>;
136
+ time: <const Opt extends TimeFieldOptions = FieldOptions>(options?: Opt) => import("@tailor-platform/sdk").TailorField<{
137
137
  type: "time";
138
138
  array: Opt extends {
139
139
  array: true;
140
140
  } ? true : false;
141
141
  }, Opt["optional"] extends true ? ([Opt] extends [{
142
142
  array: true;
143
- }] ? string[] : string) | null : [Opt] extends [{
143
+ }] ? TimeFieldValue<Opt["as"]>[] : TimeFieldValue<Opt["as"]>) | null : [Opt] extends [{
144
144
  array: true;
145
- }] ? string[] : string, FieldMetadata, TailorFieldType>;
145
+ }] ? TimeFieldValue<Opt["as"]>[] : TimeFieldValue<Opt["as"]>, FieldMetadata, TailorFieldType>;
146
146
  enum: <const V extends AllowedValues, const Opt extends FieldOptions>(values: V, options?: Opt) => import("@tailor-platform/sdk").TailorField<{
147
147
  type: "enum";
148
148
  array: Opt extends {
@@ -1,2 +1,2 @@
1
- import{r as e}from"../field-parse-CzlKC4b7.mjs";import{n as t,t as n}from"../schema-DRyQEabV.mjs";import{t as r}from"../brand-C8nMKhJC.mjs";import{a as i,n as a,r as o}from"../registry-HlEaGvl5.mjs";import{l as s,n as c,r as l,t as u}from"../wait-point-invoker-eiP-IIux.mjs";import{a as d,i as f,o as p,r as m}from"../wait-point-registry-B-ESkTZX.mjs";function createTailorField(n,r,i,a,o){let s=o?{...o,...o.allowedValues&&{allowedValues:o.allowedValues.map(e=>({...e}))},...o.validate&&{validate:o.validate.map(e=>Array.isArray(e)?[...e]:e)}}:{required:!0};o||(r&&(r.optional===!0&&(s.required=!1),r.array===!0&&(s.array=!0)),a&&(s.allowedValues=t(a)));function parseInternal$1(t){return e({...t,field:c})}function cloneWith(e){let t=c.clone();return Object.assign(t._metadata,e),t}let c={type:n,fields:i??{},_defined:void 0,_output:void 0,_metadata:s,get metadata(){return{...this._metadata}},description(e){return cloneWith({description:e})},typeName(e){return cloneWith({typeName:e})},validate(...e){return cloneWith({validate:e})},parse(e){return parseInternal$1({value:e.value,data:e.data,invoker:e.invoker,pathArray:[]})},clone(){let e=i;if(i){let t={};for(let[e,n]of Object.entries(i))t[e]=n.clone();e=t}return createTailorField(n,r,e,a,this._metadata)}};return c}function uuid(e){return createTailorField(`uuid`,e)}function string(e){return createTailorField(`string`,e)}function bool(e){return createTailorField(`boolean`,e)}function int(e){return createTailorField(`integer`,e)}function float(e){return createTailorField(`float`,e)}function decimal(e){return createTailorField(`decimal`,e)}function date(e){let t=createTailorField(`date`,e);return e?.as===`date`&&(t._metadata.as=`date`),t}function datetime(e){return createTailorField(`datetime`,e)}function time(e){return createTailorField(`time`,e)}function _enum(e,t){return createTailorField(`enum`,t,void 0,e)}function object(e,t){return createTailorField(`nested`,t,e)}const h={uuid,string,bool,int,float,decimal,date,datetime,time,enum:_enum,object};function defineAuth(e,t){return{...t,name:e}}const g={create:[{conditions:[],permit:!0}],read:[{conditions:[],permit:!0}],update:[{conditions:[],permit:!0}],delete:[{conditions:[],permit:!0}]},_=[{conditions:[],actions:`all`,permit:!0}];function createResolver(e){let t=(e=>typeof e==`object`&&!!e&&`type`in e&&typeof e.type==`string`)(e.output)?e.output:h.object(e.output);return r({...e,output:t},`resolver`)}function createExecutor(e){return r(e,`executor`)}const v={created:`tailordb.type_record.created`,updated:`tailordb.type_record.updated`,deleted:`tailordb.type_record.deleted`};function recordCreatedTrigger(e){let{type:t,condition:n}=e;return{kind:`tailordb`,events:[`tailordb.type_record.created`],tableName:t.name,condition:n,__args:{}}}function recordUpdatedTrigger(e){let{type:t,condition:n}=e;return{kind:`tailordb`,events:[`tailordb.type_record.updated`],tableName:t.name,condition:n,__args:{}}}function recordDeletedTrigger(e){let{type:t,condition:n}=e;return{kind:`tailordb`,events:[`tailordb.type_record.deleted`],tableName:t.name,condition:n,__args:{}}}function recordTrigger(e){let{type:t,events:n,condition:r}=e;return{kind:`tailordb`,events:n.map(e=>v[e]),tableName:t.name,condition:r,__args:{}}}function resolverExecutedTrigger(e){let{resolver:t,condition:n}=e;return{kind:`resolverExecuted`,resolverName:t.name,condition:n,__args:{}}}const y={created:`idp.user.created`,updated:`idp.user.updated`,deleted:`idp.user.deleted`};function idpUserCreatedTrigger(e){return{kind:`idpUser`,events:[`idp.user.created`],...e?.idp==null?{}:{idp:e.idp},__args:{}}}function idpUserUpdatedTrigger(e){return{kind:`idpUser`,events:[`idp.user.updated`],...e?.idp==null?{}:{idp:e.idp},__args:{}}}function idpUserDeletedTrigger(e){return{kind:`idpUser`,events:[`idp.user.deleted`],...e?.idp==null?{}:{idp:e.idp},__args:{}}}function idpUserTrigger(e){let{events:t,idp:n}=e;return{kind:`idpUser`,events:t.map(e=>y[e]),...n==null?{}:{idp:n},__args:{}}}const b={issued:`auth.access_token.issued`,refreshed:`auth.access_token.refreshed`,revoked:`auth.access_token.revoked`};function authAccessTokenIssuedTrigger(){return{kind:`authAccessToken`,events:[`auth.access_token.issued`],__args:{}}}function authAccessTokenRefreshedTrigger(){return{kind:`authAccessToken`,events:[`auth.access_token.refreshed`],__args:{}}}function authAccessTokenRevokedTrigger(){return{kind:`authAccessToken`,events:[`auth.access_token.revoked`],__args:{}}}function authAccessTokenTrigger(e){let{events:t}=e;return{kind:`authAccessToken`,events:t.map(e=>b[e]),__args:{}}}const x={started:`workflow.workflow_execution.started`,completed:`workflow.workflow_execution.completed`,retried:`workflow.workflow_execution.retried`,resumed:`workflow.workflow_execution.resumed`,wait_started:`workflow.workflow_execution.wait_started`,wait_resolved:`workflow.workflow_execution.wait_resolved`};function workflowExecutionTriggerConfig(e,t){return{kind:`workflowExecution`,events:e,workflowName:t.workflow.name,condition:t.condition,__args:{}}}function workflowExecutionStartedTrigger(e){return workflowExecutionTriggerConfig([`workflow.workflow_execution.started`],e)}function workflowExecutionCompletedTrigger(e){return workflowExecutionTriggerConfig([`workflow.workflow_execution.completed`],e)}function workflowExecutionRetriedTrigger(e){return workflowExecutionTriggerConfig([`workflow.workflow_execution.retried`],e)}function workflowExecutionResumedTrigger(e){return workflowExecutionTriggerConfig([`workflow.workflow_execution.resumed`],e)}function workflowExecutionWaitStartedTrigger(e){return workflowExecutionTriggerConfig([`workflow.workflow_execution.wait_started`],e)}function workflowExecutionWaitResolvedTrigger(e){return workflowExecutionTriggerConfig([`workflow.workflow_execution.wait_resolved`],e)}function workflowExecutionTrigger(e){let{events:t,workflow:n,condition:r}=e;return workflowExecutionTriggerConfig(t.map(e=>x[e]),{workflow:n,condition:r})}const S={started:`workflow.workflow_execution.job_execution.started`,completed:`workflow.workflow_execution.job_execution.completed`,wait_started:`workflow.workflow_execution.job_execution.wait_started`,wait_resolved:`workflow.workflow_execution.job_execution.wait_resolved`};function workflowJobExecutionTriggerConfig(e,t){return{kind:`workflowJobExecution`,events:e,workflowName:t.workflow.name,condition:t.condition,__args:{}}}function workflowJobExecutionStartedTrigger(e){return workflowJobExecutionTriggerConfig([`workflow.workflow_execution.job_execution.started`],e)}function workflowJobExecutionCompletedTrigger(e){return workflowJobExecutionTriggerConfig([`workflow.workflow_execution.job_execution.completed`],e)}function workflowJobExecutionWaitStartedTrigger(e){return workflowJobExecutionTriggerConfig([`workflow.workflow_execution.job_execution.wait_started`],e)}function workflowJobExecutionWaitResolvedTrigger(e){return workflowJobExecutionTriggerConfig([`workflow.workflow_execution.job_execution.wait_resolved`],e)}function workflowJobExecutionTrigger(e){let{events:t,workflow:n,condition:r}=e;return workflowJobExecutionTriggerConfig(t.map(e=>S[e]),{workflow:n,condition:r})}function scheduleTrigger(e){let{cron:t,timezone:n}=e;return{kind:`schedule`,cron:t,timezone:n,__args:{}}}function incomingWebhookTrigger(e){let t=typeof e?.response==`function`?{body:e.response}:e?.response;return{kind:`incomingWebhook`,...t?{response:t}:{},__args:{}}}const C=/^[a-z0-9][a-z0-9_:.-]{0,62}[a-z0-9]$/;function createExecutionPolicyInstance(e,t,n,i,a,o,s){let c=i===`prefix`,l={name:e,key:t,matchType:i,...n&&{concurrencyPolicy:n},...c&&{keyFor:e=>{let t=`${l.key}${a}${e}`;if(!C.test(t))throw Error(`Invalid execution policy key "${t}" built by keyFor("${e}"): must match [a-z0-9_:.-] (2-64 chars; must start and end with [a-z0-9]).`);return t}}};return{instance:r(l,`execution-policy`),setName:o?e=>{l.name=e}:void 0,setKey:s?e=>{l.key=e}:void 0}}function defineWorkflowExecutionPolicy(e,t){return createExecutionPolicyInstance(e,t?.key??e,t?.concurrencyPolicy,t?.matchType??`exact`,t?.separator??`.`,!1,!1).instance}function defineWorkflowExecutionPolicies(e,t){let n=t?.separator??`.`,r=new Map,i=new Map,a=e(e=>{let t=e?.name,a=e?.key,{instance:o,setName:s,setKey:c}=createExecutionPolicyInstance(t??`__pending__`,a??t??`__pending__`,e?.concurrencyPolicy,e?.matchType??`exact`,n,t===void 0,a===void 0&&t===void 0);return s&&r.set(o,s),c&&i.set(o,c),o});for(let e of Object.keys(a)){let t=a[e];r.get(t)?.(e),i.get(t)?.(e)}return a}function createWorkflowJob(e){let t=e.body,n=process.env.__TAILOR_PLATFORM_BUNDLE?t:(e,n)=>s(n.invoker,()=>t(e,n));process.env.__TAILOR_PLATFORM_BUNDLE||i(e.name,n);let o=process.env.__TAILOR_PLATFORM_BUNDLE?()=>{throw Error(`.start() on workflow job "${e.name}" is rewritten at build time and is unavailable in the bundle`)}:function(t,n){return arguments.length>=2?a(e.name,t,n):a(e.name,t)};return r({name:e.name,start:o,body:n,...e.publishEvents===void 0?{}:{publishEvents:e.publishEvents}},`workflow-job`)}const w=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;function parseKey(e){let t=e.split(`-`);return{segments:t,paramNames:t.filter(p).map(e=>e.slice(1))}}function composeKey(e,t,n){let r=t.segments.map(t=>{if(!p(t))return t;let r=t.slice(1),i=n[r];if(typeof i!=`string`)throw Error(`Wait point "${e}" needs a string for parameter "${r}" but received ${i===void 0?`undefined`:typeof i}.`);if(!w.test(i))throw Error(`Wait point "${e}" cannot use ${JSON.stringify(i)} for parameter "${r}": values may only contain [a-z0-9-] and cannot be empty or start or end with "-".`);return i}).join(`-`);if(r.length>63)throw Error(`Wait point key "${r}" built from "${e}" is ${r.length} characters; the limit is 63.`);if(!d.test(r))throw Error(`Wait point key "${r}" built from "${e}" must match ${f}.`);return r}function createBoundWaitPoint(e,t){return{wait(n){return Promise.resolve(e.wait(t(),n))},async resolve(n,r){await e.resolve(t(),n,r)}}}function createWaitPointInstance(e){let t=e,n=l(),i=r(createBoundWaitPoint(n,()=>t),`wait-point`);return u(i,n),{instance:i,setKey:e=>{t=e}}}function createParameterizedWaitPointInstance(e,t,n){let i=l(),unbound=()=>{throw Error(n===`define`?`Wait point key "${e}" has $params, so it identifies no single suspension on its own. Bind them first: waitPoint.with({ ... }).wait(...).`:`Wait point key "${e}" has $params, which createWaitPoint cannot type. Declare it through createWaitPoints instead: createWaitPoints((define) => ({ myWaitPoint: define.for("${e}")<Payload, Result>() })).`)},a=r({with(n){let r=composeKey(e,t,n);return c(createBoundWaitPoint(i,()=>r),r)},wait:unbound,resolve:unbound},`wait-point`);return u(a,i),a}function createKeyedWaitPoint(e,t){m({key:e,declaredBy:t});let n=parseKey(e);return n.paramNames.length>0?createParameterizedWaitPointInstance(e,n,t):createWaitPointInstance(e).instance}function createWaitPoint(e){return createKeyedWaitPoint(e,`createWaitPoint`)}function createWaitPoints(e){let t=new Map,n=e(Object.assign(()=>{let{instance:e,setKey:n}=createWaitPointInstance(`__pending__`);return t.set(e,n),e},{for:e=>{let t=createKeyedWaitPoint(e,`define`);return()=>t}}));for(let e of Object.keys(n)){let r=t.get(n[e]);r&&(m({key:e,declaredBy:`property`}),r(e))}return n}function createWorkflow(e){return r({...e,start:process.env.__TAILOR_PLATFORM_BUNDLE?async()=>{throw Error(`workflow.start() is rewritten at build time and unavailable in the bundle`)}:async function(t,n){return arguments.length>=2?await o(e.name,t,n):await o(e.name,t)}},`workflow`)}function defineStaticWebSite(e,t){return{...t,name:e,get url(){return`${e}:url`}}}function defineAIGateway(e,t){return{...t,name:e}}const T={create:[{conditions:[],permit:!0}],read:[{conditions:[],permit:!0}],update:[{conditions:[],permit:!0}],delete:[{conditions:[],permit:!0}],sendPasswordResetEmail:[{conditions:[],permit:!0}],unenrollMfa:[{conditions:[],permit:!0}]};function defineIdp(e,t){return{...t,name:e,provider(t,n){return{name:t,kind:`BuiltInIdP`,namespace:e,clientName:n}}}}function defineSecretManager(e,t){let n={vaults:e,options:{ignoreNullishValues:t?.ignoreNullishValues??!1}};return Object.defineProperty(n,"get",{value:async(e,t)=>tailor.secretmanager.getSecret(e,t),enumerable:!1}),Object.defineProperty(n,"getAll",{value:async(e,t)=>{let n=await tailor.secretmanager.getSecrets(e,t);return t.map(e=>n[e])},enumerable:!1}),n}function createHttpAdapter(e){return r({...e},`http-adapter`)}function defineConfig(e){return e}function definePlugins(...e){return e}const E=h;export{authAccessTokenIssuedTrigger,authAccessTokenRefreshedTrigger,authAccessTokenRevokedTrigger,authAccessTokenTrigger,createExecutor,createHttpAdapter,createResolver,createWaitPoint,createWaitPoints,createWorkflow,createWorkflowJob,n as db,defineAIGateway,defineAuth,defineConfig,defineIdp,definePlugins,defineSecretManager,defineStaticWebSite,defineWorkflowExecutionPolicies,defineWorkflowExecutionPolicy,idpUserCreatedTrigger,idpUserDeletedTrigger,idpUserTrigger,idpUserUpdatedTrigger,incomingWebhookTrigger,recordCreatedTrigger,recordDeletedTrigger,recordTrigger,recordUpdatedTrigger,resolverExecutedTrigger,scheduleTrigger,E as t,_ as unsafeAllowAllGqlPermission,T as unsafeAllowAllIdPPermission,g as unsafeAllowAllTypePermission,workflowExecutionCompletedTrigger,workflowExecutionResumedTrigger,workflowExecutionRetriedTrigger,workflowExecutionStartedTrigger,workflowExecutionTrigger,workflowExecutionWaitResolvedTrigger,workflowExecutionWaitStartedTrigger,workflowJobExecutionCompletedTrigger,workflowJobExecutionStartedTrigger,workflowJobExecutionTrigger,workflowJobExecutionWaitResolvedTrigger,workflowJobExecutionWaitStartedTrigger};
1
+ import{r as e}from"../field-parse-BbNyotv5.mjs";import{n as t,t as n}from"../schema-BKvcWdVf.mjs";import{t as r}from"../brand-C8nMKhJC.mjs";import{a as i,n as a,r as o}from"../registry-HlEaGvl5.mjs";import{l as s,n as c,r as l,t as u}from"../wait-point-invoker-eiP-IIux.mjs";import{a as d,i as f,o as p,r as m}from"../wait-point-registry-B-ESkTZX.mjs";function createTailorField(n,r,i,a,o){let s=o?{...o,...o.allowedValues&&{allowedValues:o.allowedValues.map(e=>({...e}))},...o.validate&&{validate:o.validate.map(e=>Array.isArray(e)?[...e]:e)}}:{required:!0};o||(r&&(r.optional===!0&&(s.required=!1),r.array===!0&&(s.array=!0)),a&&(s.allowedValues=t(a)));function parseInternal$1(t){return e({...t,field:c})}function cloneWith(e){let t=c.clone();return Object.assign(t._metadata,e),t}let c={type:n,fields:i??{},_defined:void 0,_output:void 0,_metadata:s,get metadata(){return{...this._metadata}},description(e){return cloneWith({description:e})},typeName(e){return cloneWith({typeName:e})},validate(...e){return cloneWith({validate:e})},parse(e){return parseInternal$1({value:e.value,data:e.data,invoker:e.invoker,pathArray:[]})},clone(){let e=i;if(i){let t={};for(let[e,n]of Object.entries(i))t[e]=n.clone();e=t}return createTailorField(n,r,e,a,this._metadata)}};return c}function uuid(e){return createTailorField(`uuid`,e)}function string(e){return createTailorField(`string`,e)}function bool(e){return createTailorField(`boolean`,e)}function int(e){return createTailorField(`integer`,e)}function float(e){return createTailorField(`float`,e)}function decimal(e){return createTailorField(`decimal`,e)}function date(e){let t=createTailorField(`date`,e);return(e?.as===`date`||e?.as===`temporal`)&&(t._metadata.as=e.as),t}function datetime(e){let t=createTailorField(`datetime`,e);return(e?.as===`date`||e?.as===`temporal`)&&(t._metadata.as=e.as),t}function time(e){let t=createTailorField(`time`,e);return(e?.as===`date`||e?.as===`temporal`)&&(t._metadata.as=e.as),t}function _enum(e,t){return createTailorField(`enum`,t,void 0,e)}function object(e,t){return createTailorField(`nested`,t,e)}const h={uuid,string,bool,int,float,decimal,date,datetime,time,enum:_enum,object};function defineAuth(e,t){return{...t,name:e}}const g={create:[{conditions:[],permit:!0}],read:[{conditions:[],permit:!0}],update:[{conditions:[],permit:!0}],delete:[{conditions:[],permit:!0}]},_=[{conditions:[],actions:`all`,permit:!0}];function createResolver(e){let t=(e=>typeof e==`object`&&!!e&&`type`in e&&typeof e.type==`string`)(e.output)?e.output:h.object(e.output);return r({...e,output:t},`resolver`)}function createExecutor(e){return r(e,`executor`)}const v={created:`tailordb.type_record.created`,updated:`tailordb.type_record.updated`,deleted:`tailordb.type_record.deleted`};function recordCreatedTrigger(e){let{type:t,condition:n}=e;return{kind:`tailordb`,events:[`tailordb.type_record.created`],tableName:t.name,condition:n,__args:{}}}function recordUpdatedTrigger(e){let{type:t,condition:n}=e;return{kind:`tailordb`,events:[`tailordb.type_record.updated`],tableName:t.name,condition:n,__args:{}}}function recordDeletedTrigger(e){let{type:t,condition:n}=e;return{kind:`tailordb`,events:[`tailordb.type_record.deleted`],tableName:t.name,condition:n,__args:{}}}function recordTrigger(e){let{type:t,events:n,condition:r}=e;return{kind:`tailordb`,events:n.map(e=>v[e]),tableName:t.name,condition:r,__args:{}}}function resolverExecutedTrigger(e){let{resolver:t,condition:n}=e;return{kind:`resolverExecuted`,resolverName:t.name,condition:n,__args:{}}}const y={created:`idp.user.created`,updated:`idp.user.updated`,deleted:`idp.user.deleted`};function idpUserCreatedTrigger(e){return{kind:`idpUser`,events:[`idp.user.created`],...e?.idp==null?{}:{idp:e.idp},__args:{}}}function idpUserUpdatedTrigger(e){return{kind:`idpUser`,events:[`idp.user.updated`],...e?.idp==null?{}:{idp:e.idp},__args:{}}}function idpUserDeletedTrigger(e){return{kind:`idpUser`,events:[`idp.user.deleted`],...e?.idp==null?{}:{idp:e.idp},__args:{}}}function idpUserTrigger(e){let{events:t,idp:n}=e;return{kind:`idpUser`,events:t.map(e=>y[e]),...n==null?{}:{idp:n},__args:{}}}const b={issued:`auth.access_token.issued`,refreshed:`auth.access_token.refreshed`,revoked:`auth.access_token.revoked`};function authAccessTokenIssuedTrigger(){return{kind:`authAccessToken`,events:[`auth.access_token.issued`],__args:{}}}function authAccessTokenRefreshedTrigger(){return{kind:`authAccessToken`,events:[`auth.access_token.refreshed`],__args:{}}}function authAccessTokenRevokedTrigger(){return{kind:`authAccessToken`,events:[`auth.access_token.revoked`],__args:{}}}function authAccessTokenTrigger(e){let{events:t}=e;return{kind:`authAccessToken`,events:t.map(e=>b[e]),__args:{}}}const x={started:`workflow.workflow_execution.started`,completed:`workflow.workflow_execution.completed`,retried:`workflow.workflow_execution.retried`,resumed:`workflow.workflow_execution.resumed`,wait_started:`workflow.workflow_execution.wait_started`,wait_resolved:`workflow.workflow_execution.wait_resolved`};function workflowExecutionTriggerConfig(e,t){return{kind:`workflowExecution`,events:e,workflowName:t.workflow.name,condition:t.condition,__args:{}}}function workflowExecutionStartedTrigger(e){return workflowExecutionTriggerConfig([`workflow.workflow_execution.started`],e)}function workflowExecutionCompletedTrigger(e){return workflowExecutionTriggerConfig([`workflow.workflow_execution.completed`],e)}function workflowExecutionRetriedTrigger(e){return workflowExecutionTriggerConfig([`workflow.workflow_execution.retried`],e)}function workflowExecutionResumedTrigger(e){return workflowExecutionTriggerConfig([`workflow.workflow_execution.resumed`],e)}function workflowExecutionWaitStartedTrigger(e){return workflowExecutionTriggerConfig([`workflow.workflow_execution.wait_started`],e)}function workflowExecutionWaitResolvedTrigger(e){return workflowExecutionTriggerConfig([`workflow.workflow_execution.wait_resolved`],e)}function workflowExecutionTrigger(e){let{events:t,workflow:n,condition:r}=e;return workflowExecutionTriggerConfig(t.map(e=>x[e]),{workflow:n,condition:r})}const S={started:`workflow.workflow_execution.job_execution.started`,completed:`workflow.workflow_execution.job_execution.completed`,wait_started:`workflow.workflow_execution.job_execution.wait_started`,wait_resolved:`workflow.workflow_execution.job_execution.wait_resolved`};function workflowJobExecutionTriggerConfig(e,t){return{kind:`workflowJobExecution`,events:e,workflowName:t.workflow.name,condition:t.condition,__args:{}}}function workflowJobExecutionStartedTrigger(e){return workflowJobExecutionTriggerConfig([`workflow.workflow_execution.job_execution.started`],e)}function workflowJobExecutionCompletedTrigger(e){return workflowJobExecutionTriggerConfig([`workflow.workflow_execution.job_execution.completed`],e)}function workflowJobExecutionWaitStartedTrigger(e){return workflowJobExecutionTriggerConfig([`workflow.workflow_execution.job_execution.wait_started`],e)}function workflowJobExecutionWaitResolvedTrigger(e){return workflowJobExecutionTriggerConfig([`workflow.workflow_execution.job_execution.wait_resolved`],e)}function workflowJobExecutionTrigger(e){let{events:t,workflow:n,condition:r}=e;return workflowJobExecutionTriggerConfig(t.map(e=>S[e]),{workflow:n,condition:r})}function scheduleTrigger(e){let{cron:t,timezone:n}=e;return{kind:`schedule`,cron:t,timezone:n,__args:{}}}function incomingWebhookTrigger(e){let t=typeof e?.response==`function`?{body:e.response}:e?.response;return{kind:`incomingWebhook`,...t?{response:t}:{},__args:{}}}const C=/^[a-z0-9][a-z0-9_:.-]{0,62}[a-z0-9]$/;function createExecutionPolicyInstance(e,t,n,i,a,o,s){let c=i===`prefix`,l={name:e,key:t,matchType:i,...n&&{concurrencyPolicy:n},...c&&{keyFor:e=>{let t=`${l.key}${a}${e}`;if(!C.test(t))throw Error(`Invalid execution policy key "${t}" built by keyFor("${e}"): must match [a-z0-9_:.-] (2-64 chars; must start and end with [a-z0-9]).`);return t}}};return{instance:r(l,`execution-policy`),setName:o?e=>{l.name=e}:void 0,setKey:s?e=>{l.key=e}:void 0}}function defineWorkflowExecutionPolicy(e,t){return createExecutionPolicyInstance(e,t?.key??e,t?.concurrencyPolicy,t?.matchType??`exact`,t?.separator??`.`,!1,!1).instance}function defineWorkflowExecutionPolicies(e,t){let n=t?.separator??`.`,r=new Map,i=new Map,a=e(e=>{let t=e?.name,a=e?.key,{instance:o,setName:s,setKey:c}=createExecutionPolicyInstance(t??`__pending__`,a??t??`__pending__`,e?.concurrencyPolicy,e?.matchType??`exact`,n,t===void 0,a===void 0&&t===void 0);return s&&r.set(o,s),c&&i.set(o,c),o});for(let e of Object.keys(a)){let t=a[e];r.get(t)?.(e),i.get(t)?.(e)}return a}function createWorkflowJob(e){let t=e.body,n=process.env.__TAILOR_PLATFORM_BUNDLE?t:(e,n)=>s(n.invoker,()=>t(e,n));process.env.__TAILOR_PLATFORM_BUNDLE||i(e.name,n);let o=process.env.__TAILOR_PLATFORM_BUNDLE?()=>{throw Error(`.start() on workflow job "${e.name}" is rewritten at build time and is unavailable in the bundle`)}:function(t,n){return arguments.length>=2?a(e.name,t,n):a(e.name,t)};return r({name:e.name,start:o,body:n,...e.publishEvents===void 0?{}:{publishEvents:e.publishEvents}},`workflow-job`)}const w=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;function parseKey(e){let t=e.split(`-`);return{segments:t,paramNames:t.filter(p).map(e=>e.slice(1))}}function composeKey(e,t,n){let r=t.segments.map(t=>{if(!p(t))return t;let r=t.slice(1),i=n[r];if(typeof i!=`string`)throw Error(`Wait point "${e}" needs a string for parameter "${r}" but received ${i===void 0?`undefined`:typeof i}.`);if(!w.test(i))throw Error(`Wait point "${e}" cannot use ${JSON.stringify(i)} for parameter "${r}": values may only contain [a-z0-9-] and cannot be empty or start or end with "-".`);return i}).join(`-`);if(r.length>63)throw Error(`Wait point key "${r}" built from "${e}" is ${r.length} characters; the limit is 63.`);if(!d.test(r))throw Error(`Wait point key "${r}" built from "${e}" must match ${f}.`);return r}function createBoundWaitPoint(e,t){return{wait(n){return Promise.resolve(e.wait(t(),n))},async resolve(n,r){await e.resolve(t(),n,r)}}}function createWaitPointInstance(e){let t=e,n=l(),i=r(createBoundWaitPoint(n,()=>t),`wait-point`);return u(i,n),{instance:i,setKey:e=>{t=e}}}function createParameterizedWaitPointInstance(e,t,n){let i=l(),unbound=()=>{throw Error(n===`define`?`Wait point key "${e}" has $params, so it identifies no single suspension on its own. Bind them first: waitPoint.with({ ... }).wait(...).`:`Wait point key "${e}" has $params, which createWaitPoint cannot type. Declare it through createWaitPoints instead: createWaitPoints((define) => ({ myWaitPoint: define.for("${e}")<Payload, Result>() })).`)},a=r({with(n){let r=composeKey(e,t,n);return c(createBoundWaitPoint(i,()=>r),r)},wait:unbound,resolve:unbound},`wait-point`);return u(a,i),a}function createKeyedWaitPoint(e,t){m({key:e,declaredBy:t});let n=parseKey(e);return n.paramNames.length>0?createParameterizedWaitPointInstance(e,n,t):createWaitPointInstance(e).instance}function createWaitPoint(e){return createKeyedWaitPoint(e,`createWaitPoint`)}function createWaitPoints(e){let t=new Map,n=e(Object.assign(()=>{let{instance:e,setKey:n}=createWaitPointInstance(`__pending__`);return t.set(e,n),e},{for:e=>{let t=createKeyedWaitPoint(e,`define`);return()=>t}}));for(let e of Object.keys(n)){let r=t.get(n[e]);r&&(m({key:e,declaredBy:`property`}),r(e))}return n}function createWorkflow(e){return r({...e,start:process.env.__TAILOR_PLATFORM_BUNDLE?async()=>{throw Error(`workflow.start() is rewritten at build time and unavailable in the bundle`)}:async function(t,n){return arguments.length>=2?await o(e.name,t,n):await o(e.name,t)}},`workflow`)}function defineStaticWebSite(e,t){return{...t,name:e,get url(){return`${e}:url`}}}function defineAIGateway(e,t){return{...t,name:e}}const T={create:[{conditions:[],permit:!0}],read:[{conditions:[],permit:!0}],update:[{conditions:[],permit:!0}],delete:[{conditions:[],permit:!0}],sendPasswordResetEmail:[{conditions:[],permit:!0}],unenrollMfa:[{conditions:[],permit:!0}]};function defineIdp(e,t){return{...t,name:e,provider(t,n){return{name:t,kind:`BuiltInIdP`,namespace:e,clientName:n}}}}function defineSecretManager(e,t){let n={vaults:e,options:{ignoreNullishValues:t?.ignoreNullishValues??!1}};return Object.defineProperty(n,"get",{value:async(e,t)=>tailor.secretmanager.getSecret(e,t),enumerable:!1}),Object.defineProperty(n,"getAll",{value:async(e,t)=>{let n=await tailor.secretmanager.getSecrets(e,t);return t.map(e=>n[e])},enumerable:!1}),n}function createHttpAdapter(e){return r({...e},`http-adapter`)}function defineConfig(e){return e}function definePlugins(...e){return e}const E=h;export{authAccessTokenIssuedTrigger,authAccessTokenRefreshedTrigger,authAccessTokenRevokedTrigger,authAccessTokenTrigger,createExecutor,createHttpAdapter,createResolver,createWaitPoint,createWaitPoints,createWorkflow,createWorkflowJob,n as db,defineAIGateway,defineAuth,defineConfig,defineIdp,definePlugins,defineSecretManager,defineStaticWebSite,defineWorkflowExecutionPolicies,defineWorkflowExecutionPolicy,idpUserCreatedTrigger,idpUserDeletedTrigger,idpUserTrigger,idpUserUpdatedTrigger,incomingWebhookTrigger,recordCreatedTrigger,recordDeletedTrigger,recordTrigger,recordUpdatedTrigger,resolverExecutedTrigger,scheduleTrigger,E as t,_ as unsafeAllowAllGqlPermission,T as unsafeAllowAllIdPPermission,g as unsafeAllowAllTypePermission,workflowExecutionCompletedTrigger,workflowExecutionResumedTrigger,workflowExecutionRetriedTrigger,workflowExecutionStartedTrigger,workflowExecutionTrigger,workflowExecutionWaitResolvedTrigger,workflowExecutionWaitStartedTrigger,workflowJobExecutionCompletedTrigger,workflowJobExecutionStartedTrigger,workflowJobExecutionTrigger,workflowJobExecutionWaitResolvedTrigger,workflowJobExecutionWaitStartedTrigger};
2
2
  //# sourceMappingURL=index.mjs.map