@tailor-platform/sdk 1.63.0 → 2.0.0-next.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.
@@ -3,7 +3,7 @@ import { t as db } from "./schema-1msIhXwA.mjs";
3
3
  import { $ as CreateExecutorExecutorRequestSchema, A as TailorDBGQLPermission_Permit, At as AuthSCIMAttribute_Type, B as UpdateSecretManagerSecretRequestSchema, Bt as Subgraph_ServiceType, C as WorkflowExecution_Status, Ct as AuthConnection_Type, D as UpdateTailorDBTypeRequestSchema, Dt as AuthOAuth2Client_ClientType, E as CreateTailorDBTypeRequestSchema, Et as AuthInvokerSchema, F as CreateStaticWebsiteRequestSchema, Ft as UserProfileProviderConfig_UserProfileProviderType, G as PipelineResolver_OperationType, H as CreatePipelineServiceRequestSchema, Ht as Condition_Operator, I as UpdateStaticWebsiteRequestSchema, It as CreateApplicationRequestSchema, J as IdPLang, K as CreateIdPServiceRequestSchema, Lt as GetApplicationSchemaHealthResponse_ApplicationSchemaHealthStatus, M as TailorDBType_Permission_Permit, Mt as AuthSCIMConfig_AuthorizationType, N as TailorDBType_PermitAction, O as TailorDBGQLPermission_Action, Ot as AuthOAuth2Client_GrantType, P as AddCustomDomainRequestSchema, Pt as TenantProviderConfig_TenantProviderType, R as CreateSecretManagerSecretRequestSchema, Rt as UpdateApplicationRequestSchema, S as UpdateWorkflowRequestSchema, St as UpdateUserProfileConfigRequestSchema, T as CreateTailorDBServiceRequestSchema, Tt as AuthIDPConfig_AuthType, U as UpdatePipelineResolverRequestSchema, Ut as FilterSchema, V as CreatePipelineResolverRequestSchema, Vt as ConditionSchema, W as UpdatePipelineServiceRequestSchema, Wt as PageDirection, X as IdPPermissionPermit, Y as IdPPermissionOperator, Z as FunctionExecution_Status, _ as userAgent, _t as UpdateAuthOAuth2ClientRequestSchema, a as fetchAll, at as CreateAuthHookRequestSchema, b as CreateWorkflowJobFunctionRequestSchema, bt as UpdateAuthServiceRequestSchema, ct as CreateAuthOAuth2ClientRequestSchema, dt as CreateAuthServiceRequestSchema, et as UpdateExecutorExecutorRequestSchema, f as initOperatorClient, ft as CreateTenantConfigRequestSchema, gt as UpdateAuthMachineUserRequestSchema, h as resolveStaticWebsiteUrls, ht as UpdateAuthIDPConfigRequestSchema, it as CreateAuthConnectionRequestSchema, j as TailorDBType_Permission_Operator, jt as AuthSCIMAttribute_Uniqueness, k as TailorDBGQLPermission_Operator, kt as AuthSCIMAttribute_Mutability, lt as CreateAuthSCIMConfigRequestSchema, m as platformBaseUrl, mt as UpdateAuthHookRequestSchema, nt as ExecutorTargetType, o as fetchMachineUserToken, ot as CreateAuthIDPConfigRequestSchema, pt as CreateUserProfileConfigRequestSchema, q as UpdateIdPServiceRequestSchema, rt as ExecutorTriggerType, s as fetchPaged, st as CreateAuthMachineUserRequestSchema, tt as ExecutorJobStatus, ut as CreateAuthSCIMResourceRequestSchema, v as OperatorService, vt as UpdateAuthSCIMConfigRequestSchema, w as WorkflowJobExecution_Status, wt as AuthHookPoint, x as CreateWorkflowRequestSchema, xt as UpdateTenantConfigRequestSchema, y as WorkspacePlatformUserRole, yt as UpdateAuthSCIMResourceRequestSchema, z as CreateSecretManagerVaultRequestSchema, zt as ApplicationSchemaUpdateAttemptStatus } from "./client-CobIRHl-.mjs";
4
4
  import { t as assertDefined } from "./assert-CKfwrmCV.mjs";
5
5
  import { a as parseBoolean, i as symbols, n as logger, r as styles, t as CIPromptError } from "./logger-DpJyJvNz.mjs";
6
- import { C as loadConfig, D as loadConfigPath, E as loadAccessToken, M as writePlatformConfig, O as loadWorkspaceId, S as hashFile, b as getDistDir, d as assertUniqueLocalTailorDBTypeNames, f as assertUniqueTailorDBTypeNamesWithExternal, h as platformBundleDefinePlugin, k as readPlatformConfig, l as buildExecutorArgsExpr, m as stringifyFunction, n as generatePluginFilesIfNeeded, p as TailorDBTypeSchema, r as loadApplication, s as HTTP_METHODS, t as defineApplication, u as buildResolverOperationHookExpr, y as createBundleCache } from "./application-BezXGbrU.mjs";
6
+ import { A as readPlatformConfig, C as loadConfig, D as loadConfigPath, E as loadAccessToken, N as writePlatformConfig, O as loadMachineUserName, S as hashFile, b as getDistDir, d as assertUniqueLocalTailorDBTypeNames, f as assertUniqueTailorDBTypeNamesWithExternal, h as platformBundleDefinePlugin, k as loadWorkspaceId, l as buildExecutorArgsExpr, m as stringifyFunction, n as generatePluginFilesIfNeeded, p as TailorDBTypeSchema, r as loadApplication, s as HTTP_METHODS, t as defineApplication, u as buildResolverOperationHookExpr, y as createBundleCache } from "./application-76hhIhnJ.mjs";
7
7
  import { o as loadFilesWithIgnores, t as createExecutorService } from "./service-wI3Hvrgx.mjs";
8
8
  import { t as multiline } from "./multiline-Cf9ODpr1.mjs";
9
9
  import { t as readPackageJson } from "./package-json-DcQApfPQ.mjs";
@@ -3003,7 +3003,7 @@ function parseIdPPermission(rawPermission) {
3003
3003
  function findOmittedPermitRules(permission) {
3004
3004
  if (!permission) return [];
3005
3005
  const locations = [];
3006
- for (const action of Object.keys(permission)) permission[action]?.forEach((rule, index) => {
3006
+ for (const action of Object.keys(permission)) permission[action].forEach((rule, index) => {
3007
3007
  if (isObjectFormat(rule) && rule.permit === void 0) locations.push(`${String(action)}[${index}]`);
3008
3008
  });
3009
3009
  return locations;
@@ -6411,6 +6411,317 @@ function parseMigrationNumberArg(numberStr) {
6411
6411
  throw new Error(`Invalid migration number format: ${numberStr}. Expected 4-digit format (e.g., 0001) or integer 0-9999 (e.g., 1).`);
6412
6412
  }
6413
6413
 
6414
+ //#endregion
6415
+ //#region src/cli/commands/tailordb/migrate/snapshot-schema.ts
6416
+ /**
6417
+ * Zod schemas for TailorDB migration snapshot and diff files.
6418
+ *
6419
+ * Each schema mirrors the corresponding hand-written interface from
6420
+ * snapshot-types.ts / diff-calculator.ts. Schemas are cast to
6421
+ * `z.ZodType<T>` to keep them aligned with the interfaces at compile time.
6422
+ *
6423
+ * All object schemas use `z.looseObject` so that unknown keys written
6424
+ * by newer CLI versions survive a load → save round-trip.
6425
+ */
6426
+ const snapshotHookSchema = z.looseObject({ expr: z.string() });
6427
+ const snapshotValidationSchema = z.looseObject({
6428
+ script: z.looseObject({ expr: z.string() }).optional(),
6429
+ errorMessage: z.string()
6430
+ });
6431
+ const snapshotSerialSchema = z.looseObject({
6432
+ start: z.number(),
6433
+ maxValue: z.number().optional(),
6434
+ format: z.string().optional()
6435
+ });
6436
+ const snapshotEnumValueSchema = z.looseObject({
6437
+ value: z.string(),
6438
+ description: z.string().optional()
6439
+ });
6440
+ const snapshotFieldConfigSchema = z.looseObject({
6441
+ type: z.string(),
6442
+ required: z.boolean().default(true),
6443
+ array: z.boolean().optional(),
6444
+ index: z.boolean().optional(),
6445
+ unique: z.boolean().optional(),
6446
+ allowedValues: z.array(snapshotEnumValueSchema).optional(),
6447
+ foreignKey: z.boolean().optional(),
6448
+ foreignKeyType: z.string().optional(),
6449
+ foreignKeyField: z.string().optional(),
6450
+ description: z.string().optional(),
6451
+ vector: z.boolean().optional(),
6452
+ hooks: z.looseObject({
6453
+ create: snapshotHookSchema.optional(),
6454
+ update: snapshotHookSchema.optional()
6455
+ }).optional(),
6456
+ validate: z.array(snapshotValidationSchema).optional(),
6457
+ serial: snapshotSerialSchema.optional(),
6458
+ scale: z.number().optional(),
6459
+ fields: z.lazy(() => z.record(z.string(), snapshotFieldConfigSchema)).optional()
6460
+ });
6461
+ const snapshotIndexConfigSchema = z.looseObject({
6462
+ fields: z.array(z.string()),
6463
+ unique: z.boolean().optional()
6464
+ });
6465
+ const snapshotRelationshipSchema = z.looseObject({
6466
+ targetType: z.string(),
6467
+ targetField: z.string(),
6468
+ sourceField: z.string(),
6469
+ isArray: z.boolean(),
6470
+ description: z.string()
6471
+ });
6472
+ const FIELD_REF_KEYS = [
6473
+ "user",
6474
+ "record",
6475
+ "newRecord",
6476
+ "oldRecord"
6477
+ ];
6478
+ const snapshotPermissionOperandSchema = z.unknown().refine((v) => {
6479
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return true;
6480
+ const keys = Object.keys(v);
6481
+ return FIELD_REF_KEYS.filter((k) => keys.includes(k)).length < 2;
6482
+ }, "Ambiguous field-ref operand: contains more than one of user/record/newRecord/oldRecord");
6483
+ const snapshotGqlPermissionOperandSchema = z.unknown().refine((v) => {
6484
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return true;
6485
+ const keys = Object.keys(v);
6486
+ return FIELD_REF_KEYS.filter((k) => keys.includes(k)).length < 2;
6487
+ }, "Ambiguous field-ref operand: contains more than one of user/record/newRecord/oldRecord").refine((v) => {
6488
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return true;
6489
+ const keys = Object.keys(v);
6490
+ return ![
6491
+ "record",
6492
+ "newRecord",
6493
+ "oldRecord"
6494
+ ].some((k) => keys.includes(k));
6495
+ }, "GQL permissions only support { user } field references");
6496
+ const snapshotPermissionOperatorSchema = z.string();
6497
+ const snapshotPermissionConditionSchema = z.tuple([
6498
+ snapshotPermissionOperandSchema,
6499
+ snapshotPermissionOperatorSchema,
6500
+ snapshotPermissionOperandSchema
6501
+ ]).rest(z.unknown());
6502
+ const snapshotGqlPermissionConditionSchema = z.tuple([
6503
+ snapshotGqlPermissionOperandSchema,
6504
+ snapshotPermissionOperatorSchema,
6505
+ snapshotGqlPermissionOperandSchema
6506
+ ]).rest(z.unknown());
6507
+ const snapshotActionPermissionSchema = z.looseObject({
6508
+ conditions: z.array(snapshotPermissionConditionSchema),
6509
+ description: z.string().optional(),
6510
+ permit: z.enum(["allow", "deny"])
6511
+ });
6512
+ const snapshotRecordPermissionSchema = z.looseObject({
6513
+ create: z.array(snapshotActionPermissionSchema).default([]),
6514
+ read: z.array(snapshotActionPermissionSchema).default([]),
6515
+ update: z.array(snapshotActionPermissionSchema).default([]),
6516
+ delete: z.array(snapshotActionPermissionSchema).default([])
6517
+ });
6518
+ const snapshotGqlActionSchema = z.string();
6519
+ const snapshotGqlPermissionPolicySchema = z.looseObject({
6520
+ conditions: z.array(snapshotGqlPermissionConditionSchema),
6521
+ actions: z.array(snapshotGqlActionSchema),
6522
+ permit: z.enum(["allow", "deny"]),
6523
+ description: z.string().optional()
6524
+ });
6525
+ const snapshotGqlPermissionSchema = z.array(snapshotGqlPermissionPolicySchema);
6526
+ const tailorDBSnapshotTypeSchema = z.looseObject({
6527
+ name: z.string(),
6528
+ pluralForm: z.string().optional(),
6529
+ description: z.string().optional(),
6530
+ fields: z.record(z.string(), snapshotFieldConfigSchema),
6531
+ settings: z.looseObject({
6532
+ aggregation: z.boolean().optional(),
6533
+ bulkUpsert: z.boolean().optional(),
6534
+ gqlOperations: z.looseObject({
6535
+ create: z.boolean().optional(),
6536
+ update: z.boolean().optional(),
6537
+ delete: z.boolean().optional(),
6538
+ read: z.boolean().optional()
6539
+ }).optional(),
6540
+ publishEvents: z.boolean().optional()
6541
+ }).optional(),
6542
+ indexes: z.record(z.string(), snapshotIndexConfigSchema).optional(),
6543
+ files: z.record(z.string(), z.string()).optional(),
6544
+ forwardRelationships: z.record(z.string(), snapshotRelationshipSchema).optional(),
6545
+ backwardRelationships: z.record(z.string(), snapshotRelationshipSchema).optional(),
6546
+ permissions: z.looseObject({
6547
+ record: snapshotRecordPermissionSchema.optional(),
6548
+ gql: snapshotGqlPermissionSchema.optional()
6549
+ }).optional()
6550
+ });
6551
+ const schemaSnapshotSchema = z.looseObject({
6552
+ version: z.number(),
6553
+ namespace: z.string(),
6554
+ createdAt: z.string(),
6555
+ types: z.record(z.string(), tailorDBSnapshotTypeSchema)
6556
+ });
6557
+ const typeSettingsPatchSchema = z.looseObject({
6558
+ indexes: z.record(z.string(), snapshotIndexConfigSchema).optional(),
6559
+ files: z.record(z.string(), z.string()).optional()
6560
+ });
6561
+ const snapshotPermissionStateSchema = z.looseObject({
6562
+ recordPermission: snapshotRecordPermissionSchema.optional(),
6563
+ gqlPermission: snapshotGqlPermissionSchema.optional()
6564
+ });
6565
+ const typeAddedChangeSchema = z.looseObject({
6566
+ kind: z.literal("type_added"),
6567
+ typeName: z.string(),
6568
+ reason: z.string().optional(),
6569
+ after: tailorDBSnapshotTypeSchema
6570
+ });
6571
+ const typeRemovedChangeSchema = z.looseObject({
6572
+ kind: z.literal("type_removed"),
6573
+ typeName: z.string(),
6574
+ reason: z.string().optional(),
6575
+ before: tailorDBSnapshotTypeSchema
6576
+ });
6577
+ const typeModifiedChangeSchema = z.looseObject({
6578
+ kind: z.literal("type_modified"),
6579
+ typeName: z.string(),
6580
+ reason: z.string().optional(),
6581
+ before: typeSettingsPatchSchema.optional(),
6582
+ after: typeSettingsPatchSchema.optional()
6583
+ });
6584
+ const fieldAddedChangeSchema = z.looseObject({
6585
+ kind: z.literal("field_added"),
6586
+ typeName: z.string(),
6587
+ reason: z.string().optional(),
6588
+ fieldName: z.string(),
6589
+ after: snapshotFieldConfigSchema
6590
+ });
6591
+ const fieldRemovedChangeSchema = z.looseObject({
6592
+ kind: z.literal("field_removed"),
6593
+ typeName: z.string(),
6594
+ reason: z.string().optional(),
6595
+ fieldName: z.string(),
6596
+ before: snapshotFieldConfigSchema
6597
+ });
6598
+ const fieldModifiedChangeSchema = z.looseObject({
6599
+ kind: z.literal("field_modified"),
6600
+ typeName: z.string(),
6601
+ reason: z.string().optional(),
6602
+ fieldName: z.string(),
6603
+ before: snapshotFieldConfigSchema,
6604
+ after: snapshotFieldConfigSchema
6605
+ });
6606
+ const indexAddedChangeSchema = z.looseObject({
6607
+ kind: z.literal("index_added"),
6608
+ typeName: z.string(),
6609
+ reason: z.string().optional(),
6610
+ indexName: z.string(),
6611
+ after: snapshotIndexConfigSchema
6612
+ });
6613
+ const indexRemovedChangeSchema = z.looseObject({
6614
+ kind: z.literal("index_removed"),
6615
+ typeName: z.string(),
6616
+ reason: z.string().optional(),
6617
+ indexName: z.string(),
6618
+ before: snapshotIndexConfigSchema
6619
+ });
6620
+ const indexModifiedChangeSchema = z.looseObject({
6621
+ kind: z.literal("index_modified"),
6622
+ typeName: z.string(),
6623
+ reason: z.string().optional(),
6624
+ indexName: z.string(),
6625
+ before: snapshotIndexConfigSchema,
6626
+ after: snapshotIndexConfigSchema
6627
+ });
6628
+ const fileAddedChangeSchema = z.looseObject({
6629
+ kind: z.literal("file_added"),
6630
+ typeName: z.string(),
6631
+ reason: z.string().optional(),
6632
+ fieldName: z.string(),
6633
+ after: z.string()
6634
+ });
6635
+ const fileRemovedChangeSchema = z.looseObject({
6636
+ kind: z.literal("file_removed"),
6637
+ typeName: z.string(),
6638
+ reason: z.string().optional(),
6639
+ fieldName: z.string(),
6640
+ before: z.string()
6641
+ });
6642
+ const fileModifiedChangeSchema = z.looseObject({
6643
+ kind: z.literal("file_modified"),
6644
+ typeName: z.string(),
6645
+ reason: z.string().optional(),
6646
+ fieldName: z.string(),
6647
+ before: z.string(),
6648
+ after: z.string()
6649
+ });
6650
+ const relationshipAddedChangeSchema = z.looseObject({
6651
+ kind: z.literal("relationship_added"),
6652
+ typeName: z.string(),
6653
+ reason: z.string().optional(),
6654
+ relationshipName: z.string(),
6655
+ relationshipType: z.enum(["forward", "backward"]).optional(),
6656
+ after: snapshotRelationshipSchema
6657
+ });
6658
+ const relationshipRemovedChangeSchema = z.looseObject({
6659
+ kind: z.literal("relationship_removed"),
6660
+ typeName: z.string(),
6661
+ reason: z.string().optional(),
6662
+ relationshipName: z.string(),
6663
+ relationshipType: z.enum(["forward", "backward"]).optional(),
6664
+ before: snapshotRelationshipSchema
6665
+ });
6666
+ const relationshipModifiedChangeSchema = z.looseObject({
6667
+ kind: z.literal("relationship_modified"),
6668
+ typeName: z.string(),
6669
+ reason: z.string().optional(),
6670
+ relationshipName: z.string(),
6671
+ relationshipType: z.enum(["forward", "backward"]).optional(),
6672
+ before: snapshotRelationshipSchema,
6673
+ after: snapshotRelationshipSchema
6674
+ });
6675
+ const permissionModifiedChangeSchema = z.looseObject({
6676
+ kind: z.literal("permission_modified"),
6677
+ typeName: z.string(),
6678
+ reason: z.string().optional(),
6679
+ before: snapshotPermissionStateSchema.optional(),
6680
+ after: snapshotPermissionStateSchema.optional()
6681
+ });
6682
+ const diffChangeSchema = z.discriminatedUnion("kind", [
6683
+ typeAddedChangeSchema,
6684
+ typeRemovedChangeSchema,
6685
+ typeModifiedChangeSchema,
6686
+ fieldAddedChangeSchema,
6687
+ fieldRemovedChangeSchema,
6688
+ fieldModifiedChangeSchema,
6689
+ indexAddedChangeSchema,
6690
+ indexRemovedChangeSchema,
6691
+ indexModifiedChangeSchema,
6692
+ fileAddedChangeSchema,
6693
+ fileRemovedChangeSchema,
6694
+ fileModifiedChangeSchema,
6695
+ relationshipAddedChangeSchema,
6696
+ relationshipRemovedChangeSchema,
6697
+ relationshipModifiedChangeSchema,
6698
+ permissionModifiedChangeSchema
6699
+ ]);
6700
+ const breakingChangeInfoSchema = z.looseObject({
6701
+ typeName: z.string(),
6702
+ fieldName: z.string().optional(),
6703
+ reason: z.string(),
6704
+ unsupported: z.boolean().optional(),
6705
+ showThreeStepHint: z.boolean().optional()
6706
+ });
6707
+ const warningChangeInfoSchema = z.looseObject({
6708
+ typeName: z.string(),
6709
+ fieldName: z.string().optional(),
6710
+ reason: z.string()
6711
+ });
6712
+ const migrationDiffSchema = z.looseObject({
6713
+ version: z.number(),
6714
+ namespace: z.string(),
6715
+ createdAt: z.string(),
6716
+ description: z.string().optional(),
6717
+ changes: z.array(diffChangeSchema),
6718
+ hasBreakingChanges: z.boolean(),
6719
+ breakingChanges: z.array(breakingChangeInfoSchema),
6720
+ hasWarnings: z.boolean().optional(),
6721
+ warnings: z.array(warningChangeInfoSchema).optional(),
6722
+ requiresMigrationScript: z.boolean()
6723
+ });
6724
+
6414
6725
  //#endregion
6415
6726
  //#region src/cli/commands/tailordb/migrate/snapshot-types.ts
6416
6727
  /**
@@ -6620,21 +6931,19 @@ function createSnapshotType(type) {
6620
6931
  fields
6621
6932
  };
6622
6933
  if (type.description) snapshotType.description = type.description;
6623
- if (type.settings) {
6624
- snapshotType.settings = {};
6625
- if (type.settings.aggregation !== void 0) snapshotType.settings.aggregation = type.settings.aggregation;
6626
- if (type.settings.bulkUpsert !== void 0) snapshotType.settings.bulkUpsert = type.settings.bulkUpsert;
6627
- if (type.settings.gqlOperations) {
6628
- const ops = type.settings.gqlOperations;
6629
- snapshotType.settings.gqlOperations = {
6630
- ...ops.create !== void 0 && { create: ops.create },
6631
- ...ops.update !== void 0 && { update: ops.update },
6632
- ...ops.delete !== void 0 && { delete: ops.delete },
6633
- ...ops.read !== void 0 && { read: ops.read }
6634
- };
6635
- }
6636
- if (type.settings.publishEvents !== void 0) snapshotType.settings.publishEvents = type.settings.publishEvents;
6934
+ snapshotType.settings = {};
6935
+ if (type.settings.aggregation !== void 0) snapshotType.settings.aggregation = type.settings.aggregation;
6936
+ if (type.settings.bulkUpsert !== void 0) snapshotType.settings.bulkUpsert = type.settings.bulkUpsert;
6937
+ if (type.settings.gqlOperations) {
6938
+ const ops = type.settings.gqlOperations;
6939
+ snapshotType.settings.gqlOperations = {
6940
+ ...ops.create !== void 0 && { create: ops.create },
6941
+ ...ops.update !== void 0 && { update: ops.update },
6942
+ ...ops.delete !== void 0 && { delete: ops.delete },
6943
+ ...ops.read !== void 0 && { read: ops.read }
6944
+ };
6637
6945
  }
6946
+ if (type.settings.publishEvents !== void 0) snapshotType.settings.publishEvents = type.settings.publishEvents;
6638
6947
  if (type.indexes && Object.keys(type.indexes).length > 0) {
6639
6948
  snapshotType.indexes = {};
6640
6949
  for (const [indexName, indexConfig] of Object.entries(type.indexes)) snapshotType.indexes[indexName] = {
@@ -6715,7 +7024,15 @@ function createSnapshotFromLocalTypes(types, namespace) {
6715
7024
  */
6716
7025
  function loadSnapshot(filePath) {
6717
7026
  const content = fs$1.readFileSync(filePath, "utf-8");
6718
- const snapshot = JSON.parse(content);
7027
+ let raw;
7028
+ try {
7029
+ raw = JSON.parse(content);
7030
+ } catch (error) {
7031
+ throw new Error(`Invalid schema snapshot at ${filePath}: ${String(error)}`, { cause: error });
7032
+ }
7033
+ const result = schemaSnapshotSchema.safeParse(raw);
7034
+ if (!result.success) throw new Error(`Invalid schema snapshot at ${filePath}: ${z.prettifyError(result.error)}`, { cause: result.error });
7035
+ const snapshot = result.data;
6719
7036
  for (const type of Object.values(snapshot.types)) normalizeSnapshotType(type);
6720
7037
  return snapshot;
6721
7038
  }
@@ -6726,7 +7043,15 @@ function loadSnapshot(filePath) {
6726
7043
  */
6727
7044
  function loadDiff(filePath) {
6728
7045
  const content = fs$1.readFileSync(filePath, "utf-8");
6729
- const parsed = JSON.parse(content);
7046
+ let raw;
7047
+ try {
7048
+ raw = JSON.parse(content);
7049
+ } catch (error) {
7050
+ throw new Error(`Invalid migration diff at ${filePath}: ${String(error)}`, { cause: error });
7051
+ }
7052
+ const result = migrationDiffSchema.safeParse(raw);
7053
+ if (!result.success) throw new Error(`Invalid migration diff at ${filePath}: ${z.prettifyError(result.error)}`, { cause: result.error });
7054
+ const parsed = result.data;
6730
7055
  const warnings = parsed.warnings ?? [];
6731
7056
  return {
6732
7057
  ...parsed,
@@ -6804,7 +7129,7 @@ function applyDiffToSnapshot(snapshot, diff) {
6804
7129
  case "field_added":
6805
7130
  case "field_modified": {
6806
7131
  const existing = types[change.typeName];
6807
- if (existing && change.fieldName) types[change.typeName] = {
7132
+ if (existing) types[change.typeName] = {
6808
7133
  ...existing,
6809
7134
  fields: {
6810
7135
  ...existing.fields,
@@ -6815,7 +7140,7 @@ function applyDiffToSnapshot(snapshot, diff) {
6815
7140
  }
6816
7141
  case "field_removed": {
6817
7142
  const existing = types[change.typeName];
6818
- if (existing && change.fieldName) {
7143
+ if (existing) {
6819
7144
  const { [change.fieldName]: _, ...remainingFields } = existing.fields;
6820
7145
  types[change.typeName] = {
6821
7146
  ...existing,
@@ -6827,7 +7152,7 @@ function applyDiffToSnapshot(snapshot, diff) {
6827
7152
  case "index_added":
6828
7153
  case "index_modified": {
6829
7154
  const existing = types[change.typeName];
6830
- if (existing && change.indexName) types[change.typeName] = {
7155
+ if (existing) types[change.typeName] = {
6831
7156
  ...existing,
6832
7157
  indexes: {
6833
7158
  ...existing.indexes,
@@ -6838,7 +7163,7 @@ function applyDiffToSnapshot(snapshot, diff) {
6838
7163
  }
6839
7164
  case "index_removed": {
6840
7165
  const existing = types[change.typeName];
6841
- if (existing && change.indexName && existing.indexes) {
7166
+ if (existing && existing.indexes) {
6842
7167
  const { [change.indexName]: _, ...remainingIndexes } = existing.indexes;
6843
7168
  types[change.typeName] = {
6844
7169
  ...existing,
@@ -6850,7 +7175,7 @@ function applyDiffToSnapshot(snapshot, diff) {
6850
7175
  case "file_added":
6851
7176
  case "file_modified": {
6852
7177
  const existing = types[change.typeName];
6853
- if (existing && change.fieldName) types[change.typeName] = {
7178
+ if (existing) types[change.typeName] = {
6854
7179
  ...existing,
6855
7180
  files: {
6856
7181
  ...existing.files,
@@ -6861,7 +7186,7 @@ function applyDiffToSnapshot(snapshot, diff) {
6861
7186
  }
6862
7187
  case "file_removed": {
6863
7188
  const existing = types[change.typeName];
6864
- if (existing && change.fieldName && existing.files) {
7189
+ if (existing && existing.files) {
6865
7190
  const { [change.fieldName]: _, ...remainingFiles } = existing.files;
6866
7191
  types[change.typeName] = {
6867
7192
  ...existing,
@@ -6873,7 +7198,7 @@ function applyDiffToSnapshot(snapshot, diff) {
6873
7198
  case "relationship_added":
6874
7199
  case "relationship_modified": {
6875
7200
  const existing = types[change.typeName];
6876
- if (existing && change.relationshipName) {
7201
+ if (existing) {
6877
7202
  const rel = change.after;
6878
7203
  if ((change.relationshipType ?? (existing.forwardRelationships?.[change.relationshipName] ? "forward" : existing.backwardRelationships?.[change.relationshipName] ? "backward" : "forward")) === "forward") types[change.typeName] = {
6879
7204
  ...existing,
@@ -6894,7 +7219,7 @@ function applyDiffToSnapshot(snapshot, diff) {
6894
7219
  }
6895
7220
  case "relationship_removed": {
6896
7221
  const type = types[change.typeName];
6897
- if (type && change.relationshipName) {
7222
+ if (type) {
6898
7223
  const targetType = change.relationshipType ?? (type.forwardRelationships?.[change.relationshipName] ? "forward" : type.backwardRelationships?.[change.relationshipName] ? "backward" : null);
6899
7224
  if (targetType === "forward" && type.forwardRelationships?.[change.relationshipName]) {
6900
7225
  const { [change.relationshipName]: _, ...remaining } = type.forwardRelationships;
@@ -7004,7 +7329,7 @@ function areFieldsDifferent(oldField, newField) {
7004
7329
  for (let i = 0; i < oldValidate.length; i++) {
7005
7330
  const oldV = assertDefined(oldValidate[i], `oldValidate missing index ${i}`);
7006
7331
  const newV = assertDefined(newValidate[i], `newValidate missing index ${i}`);
7007
- if (oldV.script.expr !== newV.script.expr) return true;
7332
+ if ((oldV.script?.expr ?? "") !== (newV.script?.expr ?? "")) return true;
7008
7333
  if (oldV.errorMessage !== newV.errorMessage) return true;
7009
7334
  }
7010
7335
  const oldSerial = oldField.serial;
@@ -7452,7 +7777,7 @@ function convertRemoteFieldsToSnapshot(remoteType) {
7452
7777
  if (remoteField.foreignKeyType) config.foreignKeyType = remoteField.foreignKeyType;
7453
7778
  if (remoteField.foreignKeyField) config.foreignKeyField = remoteField.foreignKeyField;
7454
7779
  }
7455
- if (remoteField.allowedValues && remoteField.allowedValues.length > 0) config.allowedValues = remoteField.allowedValues.map((v) => ({
7780
+ if (remoteField.allowedValues.length > 0) config.allowedValues = remoteField.allowedValues.map((v) => ({
7456
7781
  value: v.value,
7457
7782
  ...v.description && { description: v.description }
7458
7783
  }));
@@ -7463,7 +7788,7 @@ function convertRemoteFieldsToSnapshot(remoteType) {
7463
7788
  if (remoteField.hooks.create?.expr) config.hooks.create = { expr: remoteField.hooks.create.expr };
7464
7789
  if (remoteField.hooks.update?.expr) config.hooks.update = { expr: remoteField.hooks.update.expr };
7465
7790
  }
7466
- if (remoteField.validate && remoteField.validate.length > 0) config.validate = remoteField.validate.map((v) => ({
7791
+ if (remoteField.validate.length > 0) config.validate = remoteField.validate.map((v) => ({
7467
7792
  script: { expr: v.script?.expr ?? "" },
7468
7793
  errorMessage: v.errorMessage ?? ""
7469
7794
  }));
@@ -7687,7 +8012,7 @@ function convertFieldConfigToProto(config) {
7687
8012
  foreignKey: config.foreignKey ?? false,
7688
8013
  foreignKeyType: config.foreignKeyType,
7689
8014
  foreignKeyField: config.foreignKeyField,
7690
- required: config.required ?? true,
8015
+ required: config.required,
7691
8016
  vector: config.vector ?? false,
7692
8017
  ...toProtoSnapshotFieldHooks(config),
7693
8018
  ...config.serial && { serial: {
@@ -7704,7 +8029,7 @@ function toProtoSnapshotFieldValidate(config) {
7704
8029
  return (config.validate ?? []).map((val) => ({
7705
8030
  action: TailorDBType_PermitAction.DENY,
7706
8031
  errorMessage: val.errorMessage || "",
7707
- ...val.script && { script: { expr: val.script.expr ? `!${val.script.expr}` : "" } }
8032
+ script: { expr: val.script && val.script.expr ? `!${val.script.expr}` : "" }
7708
8033
  }));
7709
8034
  }
7710
8035
  function toProtoSnapshotFieldHooks(config) {
@@ -7728,7 +8053,7 @@ function processNestedFieldsFromSnapshot(fields) {
7728
8053
  allowedValues: fieldConfig.allowedValues?.map((v) => ({ ...v })) ?? [],
7729
8054
  description: fieldConfig.description || "",
7730
8055
  validate: toProtoSnapshotFieldValidate(fieldConfig),
7731
- required: fieldConfig.required ?? true,
8056
+ required: fieldConfig.required,
7732
8057
  array: fieldConfig.array ?? false,
7733
8058
  index: false,
7734
8059
  unique: false,
@@ -7743,7 +8068,7 @@ function processNestedFieldsFromSnapshot(fields) {
7743
8068
  allowedValues: fieldConfig.type === "enum" ? fieldConfig.allowedValues?.map((v) => ({ ...v })) ?? [] : [],
7744
8069
  description: fieldConfig.description || "",
7745
8070
  validate: toProtoSnapshotFieldValidate(fieldConfig),
7746
- required: fieldConfig.required ?? true,
8071
+ required: fieldConfig.required,
7747
8072
  array: fieldConfig.array ?? false,
7748
8073
  index: false,
7749
8074
  unique: false,
@@ -8104,19 +8429,19 @@ function buildPreMigrationChangesMap(pendingMigrations) {
8104
8429
  function applyPreMigrationFieldAdjustments(fields, typeChanges) {
8105
8430
  for (const [fieldName, change] of typeChanges) {
8106
8431
  if (change.kind === "field_removed") {
8107
- if (change.before) fields[fieldName] = convertFieldConfigToProto(change.before);
8432
+ fields[fieldName] = convertFieldConfigToProto(change.before);
8108
8433
  continue;
8109
8434
  }
8110
8435
  const field = fields[fieldName];
8111
8436
  if (!field) continue;
8112
8437
  if (change.kind === "field_added") {
8113
- if (change.after?.required) field.required = false;
8438
+ if (change.after.required) field.required = false;
8114
8439
  continue;
8115
8440
  }
8116
8441
  const { before, after } = change;
8117
- if (!before?.required && after?.required) field.required = false;
8118
- if (!(before?.unique ?? false) && (after?.unique ?? false)) field.unique = false;
8119
- if (before?.allowedValues && after?.allowedValues) {
8442
+ if (!before.required && after.required) field.required = false;
8443
+ if (!(before.unique ?? false) && (after.unique ?? false)) field.unique = false;
8444
+ if (before.allowedValues && after.allowedValues) {
8120
8445
  const afterValues = new Set(after.allowedValues.map((v) => v.value));
8121
8446
  if (before.allowedValues.filter((v) => !afterValues.has(v.value)).length > 0) {
8122
8447
  const valueMap = /* @__PURE__ */ new Map();
@@ -8885,8 +9210,17 @@ async function applyTailorDB(client, result, phase = "create-update") {
8885
9210
  logger.newline();
8886
9211
  }
8887
9212
  for (const migration of pendingMigrations) {
8888
- await executeSingleMigrationPrePhase(client, changeSet, migration, migrationContext.tailorDBInputs, migrationContext.executorUsedTypes);
8889
- if (migration.hasScript && migrationCtx) await executeMigrations(migrationCtx, [migration]);
9213
+ try {
9214
+ await executeSingleMigrationPrePhase(client, changeSet, migration, migrationContext.tailorDBInputs, migrationContext.executorUsedTypes);
9215
+ if (migration.hasScript && migrationCtx) await executeMigrations(migrationCtx, [migration]);
9216
+ } catch (error) {
9217
+ try {
9218
+ await rollbackSingleMigrationPrePhase(client, changeSet, migration, migrationContext.workspaceId, migrationContext.tailorDBInputs, migrationContext.executorUsedTypes);
9219
+ } catch (rollbackError) {
9220
+ logger.warn(`Failed to roll back migration ${migration.namespace}/${formatMigrationNumber(migration.number)}: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`);
9221
+ }
9222
+ throw error;
9223
+ }
8890
9224
  await executeSingleMigrationPostPhase(client, changeSet, migration, migrationContext.tailorDBInputs, migrationContext.executorUsedTypes);
8891
9225
  await updateMigrationLabel(client, migrationContext.workspaceId, migration.namespace, migration.number);
8892
9226
  }
@@ -9007,6 +9341,17 @@ function buildSnapshotTypeManifest(migration, typeName, tailorDBInputs, executor
9007
9341
  });
9008
9342
  }
9009
9343
  /**
9344
+ * Await every promise to settle, then throw the first rejection. Unlike
9345
+ * `Promise.all`, this never leaves sibling operations in flight after a failure,
9346
+ * so a following rollback cannot race with still-pending DDL.
9347
+ * @param promises - Promises (or already-resolved values) to await
9348
+ * @returns {Promise<void>} Resolves once all settle; rejects with the first failure
9349
+ */
9350
+ async function awaitAllSettledOrThrow(promises) {
9351
+ const rejected = (await Promise.allSettled(promises)).find((r) => r.status === "rejected");
9352
+ if (rejected) throw rejected.reason;
9353
+ }
9354
+ /**
9010
9355
  * Execute pre-migration phase for a single migration
9011
9356
  * @param {OperatorClient} client - Operator client instance
9012
9357
  * @param {TailorDBChangeSet} changeSet - TailorDB change set
@@ -9019,7 +9364,7 @@ async function executeSingleMigrationPrePhase(client, changeSet, migration, tail
9019
9364
  const preMigrationChanges = buildPreMigrationChangesMap([migration]);
9020
9365
  const affectedTypes = getAffectedTypeNames(migration);
9021
9366
  const createdBeforeMigration = new Set(processedTypes.created);
9022
- await Promise.all([
9367
+ await awaitAllSettledOrThrow([
9023
9368
  ...changeSet.type.creates.filter((create) => {
9024
9369
  const typeName = create.request.tailordbType?.name;
9025
9370
  return typeName && affectedTypes.has(typeName) && !createdBeforeMigration.has(typeName);
@@ -9074,13 +9419,13 @@ async function executeSingleMigrationPrePhase(client, changeSet, migration, tail
9074
9419
  const typeName = create.request.tailordbType?.name;
9075
9420
  return create.request.namespaceName === migration.namespace && typeName && gqlPermissionTypeNames.has(typeName) && !processedTypes.created.has(typeName);
9076
9421
  });
9077
- if (missingTypeCreates.length > 0) await Promise.all(missingTypeCreates.map((create) => {
9422
+ if (missingTypeCreates.length > 0) await awaitAllSettledOrThrow(missingTypeCreates.map((create) => {
9078
9423
  const typeName = create.request.tailordbType?.name;
9079
9424
  if (typeName) processedTypes.created.add(typeName);
9080
9425
  return client.createTailorDBType(create.request);
9081
9426
  }));
9082
9427
  processedTypes.gqlPermissionsProcessed.add(migration.namespace);
9083
- await Promise.all([...gqlPermissionCreatesForNamespace.map((create) => client.createTailorDBGQLPermission(create.request)), ...gqlPermissionUpdatesForNamespace.map((update) => client.updateTailorDBGQLPermission(update.request))]);
9428
+ await awaitAllSettledOrThrow([...gqlPermissionCreatesForNamespace.map((create) => client.createTailorDBGQLPermission(create.request)), ...gqlPermissionUpdatesForNamespace.map((update) => client.updateTailorDBGQLPermission(update.request))]);
9084
9429
  }
9085
9430
  }
9086
9431
  /**
@@ -9161,6 +9506,67 @@ async function executeSingleMigrationPostPhase(client, changeSet, migration, tai
9161
9506
  }
9162
9507
  }
9163
9508
  /**
9509
+ * Revert a single migration's Pre-phase DDL to the prior checkpoint's schema.
9510
+ * @param client - Operator client instance
9511
+ * @param changeSet - TailorDB change set
9512
+ * @param migration - The migration whose Pre-phase DDL must be reverted
9513
+ * @param workspaceId - Workspace ID
9514
+ * @param tailorDBInputs - Deploy inputs, used to resolve namespace gqlOperations for the snapshot
9515
+ * @param executorUsedTypes - Types used by executors (drives publishRecordEvents default)
9516
+ * @returns {Promise<void>} Promise that resolves when rollback attempts complete
9517
+ */
9518
+ async function rollbackSingleMigrationPrePhase(client, changeSet, migration, workspaceId, tailorDBInputs, executorUsedTypes) {
9519
+ if (migration.number <= 0) return;
9520
+ const namespaceTypes = getAffectedTypeNames(migration);
9521
+ for (const create of changeSet.type.creates) {
9522
+ const name = create.request.tailordbType?.name;
9523
+ if (create.request.namespaceName === migration.namespace && name) namespaceTypes.add(name);
9524
+ }
9525
+ for (const update of changeSet.type.updates) {
9526
+ const name = update.request.tailordbType?.name;
9527
+ if (update.request.namespaceName === migration.namespace && name) namespaceTypes.add(name);
9528
+ }
9529
+ const applied = new Set([...processedTypes.created, ...processedTypes.updated]);
9530
+ const rollbackTypes = new Set([...namespaceTypes].filter((name) => applied.has(name)));
9531
+ if (rollbackTypes.size === 0) return;
9532
+ const priorSnapshot = reconstructSnapshotFromMigrations(migration.migrationsDir, migration.number - 1);
9533
+ if (!priorSnapshot) {
9534
+ logger.warn(`Cannot roll back migration ${migration.namespace}/${formatMigrationNumber(migration.number)}: prior snapshot (migration ${formatMigrationNumber(migration.number - 1)}) could not be reconstructed. Leaving schema as-is; manual repair may be required.`);
9535
+ return;
9536
+ }
9537
+ const input = tailorDBInputs.find((i) => i.namespace === migration.namespace);
9538
+ logger.warn(`Migration ${migration.namespace}/${formatMigrationNumber(migration.number)} failed; rolling back its pre-migration schema changes.`);
9539
+ for (const typeName of rollbackTypes) {
9540
+ const priorType = priorSnapshot.types[typeName];
9541
+ try {
9542
+ if (priorType) {
9543
+ const manifest = generateTailorDBTypeManifestFromSnapshot(priorType, {
9544
+ publishRecordEvents: executorUsedTypes.has(priorType.name),
9545
+ namespaceGqlOperations: input?.config.gqlOperations
9546
+ });
9547
+ await client.updateTailorDBType({
9548
+ workspaceId,
9549
+ namespaceName: migration.namespace,
9550
+ tailordbType: manifest
9551
+ });
9552
+ } else {
9553
+ await client.deleteTailorDBGQLPermission({
9554
+ workspaceId,
9555
+ namespaceName: migration.namespace,
9556
+ typeName
9557
+ }).catch(() => void 0);
9558
+ await client.deleteTailorDBType({
9559
+ workspaceId,
9560
+ namespaceName: migration.namespace,
9561
+ tailordbTypeName: typeName
9562
+ });
9563
+ }
9564
+ } catch (rollbackError) {
9565
+ logger.warn(`Failed to roll back type '${typeName}' in namespace '${migration.namespace}': ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`);
9566
+ }
9567
+ }
9568
+ }
9569
+ /**
9164
9570
  * Convert a runtime TailorDBService to the snapshot-shaped deploy input.
9165
9571
  * @param service - Loaded TailorDB service (after `loadTypes()`)
9166
9572
  * @returns The canonical snapshot-shaped deploy input for downstream plan/apply phases.
@@ -9579,17 +9985,7 @@ async function checkMigrationDiffs(typesByNamespace, namespacesWithMigrations) {
9579
9985
  for (const { namespace, migrationsDir } of namespacesWithMigrations) {
9580
9986
  const localTypes = typesByNamespace.get(namespace);
9581
9987
  if (!localTypes) continue;
9582
- let previousSnapshot;
9583
- try {
9584
- previousSnapshot = reconstructSnapshotFromMigrations(migrationsDir);
9585
- } catch {
9586
- results.push({
9587
- namespace,
9588
- migrationsDir,
9589
- hasDiff: false
9590
- });
9591
- continue;
9592
- }
9988
+ const previousSnapshot = reconstructSnapshotFromMigrations(migrationsDir);
9593
9989
  if (!previousSnapshot) {
9594
9990
  results.push({
9595
9991
  namespace,
@@ -9677,7 +10073,7 @@ async function applyWorkflow(client, result, phase = "create-update") {
9677
10073
  workflowId: del.workflowId
9678
10074
  })
9679
10075
  })));
9680
- await deleteAllSettled((result.jobFunctionDeletes ?? collectDeletableJobFunctions(changeSet.deletes)).map((del) => ({
10076
+ await deleteAllSettled(result.jobFunctionDeletes.map((del) => ({
9681
10077
  resourceType: "workflow job function",
9682
10078
  resourceName: del.jobFunctionName,
9683
10079
  run: () => client.deleteWorkflowJobFunction({
@@ -9704,20 +10100,6 @@ async function deleteAllSettled(operations) {
9704
10100
  const firstError = errors[0];
9705
10101
  if (firstError) throw firstError;
9706
10102
  }
9707
- function collectDeletableJobFunctions(deletes) {
9708
- const seen = /* @__PURE__ */ new Set();
9709
- const jobFunctions = [];
9710
- for (const del of deletes) for (const jobFunctionName of del.deletableJobNames) {
9711
- const key = `${del.workspaceId}\0${jobFunctionName}`;
9712
- if (seen.has(key)) continue;
9713
- seen.add(key);
9714
- jobFunctions.push({
9715
- workspaceId: del.workspaceId,
9716
- jobFunctionName
9717
- });
9718
- }
9719
- return jobFunctions;
9720
- }
9721
10103
  /**
9722
10104
  * Filter job function versions to only include those used by a workflow
9723
10105
  * @param allVersions - Map of job function names to versions
@@ -10262,7 +10644,7 @@ async function shouldForceApplyAll(client, workspaceId, application, functionEnt
10262
10644
  });
10263
10645
  for (const trn of candidateTrns) try {
10264
10646
  const { metadata } = await client.getMetadata({ trn });
10265
- if (metadata?.labels?.["sdk-name"] !== application.name) continue;
10647
+ if (metadata?.labels["sdk-name"] !== application.name) continue;
10266
10648
  if (!hasMatchingSdkVersion(metadata.labels, desiredLabels)) return true;
10267
10649
  } catch (error) {
10268
10650
  if (error instanceof ConnectError && error.code === Code.NotFound) continue;
@@ -10803,7 +11185,7 @@ function formatSubjectEvent(subject, eventTypes) {
10803
11185
  }
10804
11186
  function formatTypedEventTrigger(config) {
10805
11187
  const typedConfig = config.typedConfig;
10806
- if (!typedConfig || typedConfig.case === void 0) return null;
11188
+ if (typedConfig.case === void 0) return null;
10807
11189
  switch (typedConfig.case) {
10808
11190
  case "tailordb": return formatSubjectEvent(typedConfig.value.typeName, typedConfig.value.eventTypes);
10809
11191
  case "pipeline": return formatSubjectEvent(typedConfig.value.resolverName, typedConfig.value.eventTypes);
@@ -10875,7 +11257,7 @@ function formatTriggerConfig(executor) {
10875
11257
  }
10876
11258
  function formatEventTriggerConfig(config) {
10877
11259
  const typedConfig = config.typedConfig;
10878
- if (!typedConfig || typedConfig.case === void 0) return {
11260
+ if (typedConfig.case === void 0) return {
10879
11261
  eventType: config.eventType,
10880
11262
  condition: config.condition?.expr || ""
10881
11263
  };
@@ -11587,6 +11969,11 @@ async function startWorkflowCore(options) {
11587
11969
  }
11588
11970
  }
11589
11971
  async function startWorkflowByName(options) {
11972
+ const machineUser = await loadMachineUserName({
11973
+ machineUser: options.machineUser,
11974
+ profile: options.profile
11975
+ });
11976
+ if (!machineUser) throw new Error("Machine user is required. Specify --machine-user, set TAILOR_PLATFORM_MACHINE_USER_NAME, or set a profile default with 'tailor-sdk profile update <profile> --machine-user <name>'.");
11590
11977
  const client = await initOperatorClient(await loadAccessToken({ profile: options.profile }));
11591
11978
  const workspaceId = await loadWorkspaceId({
11592
11979
  workspaceId: options.workspaceId,
@@ -11604,7 +11991,7 @@ async function startWorkflowByName(options) {
11604
11991
  workflowName: options.name,
11605
11992
  authInvoker: {
11606
11993
  namespace: application.authNamespace,
11607
- machineUserName: options.machineUser
11994
+ machineUserName: machineUser
11608
11995
  },
11609
11996
  arg: options.arg,
11610
11997
  interval: options.interval
@@ -11630,10 +12017,10 @@ const startCommand = defineAppCommand({
11630
12017
  args: z.object({
11631
12018
  ...deploymentArgs,
11632
12019
  ...nameArgs,
11633
- "machine-user": arg(z.string(), {
12020
+ "machine-user": arg(z.string().optional(), {
11634
12021
  alias: "m",
11635
12022
  hiddenAlias: "machineuser",
11636
- description: "Machine user name",
12023
+ description: "Machine user name. Falls back to the active profile's default machine user.",
11637
12024
  env: "TAILOR_PLATFORM_MACHINE_USER_NAME"
11638
12025
  }),
11639
12026
  arg: arg(z.string().optional(), {
@@ -13458,6 +13845,11 @@ const listCommand$7 = defineAppCommand({
13458
13845
  * @returns Machine user token info
13459
13846
  */
13460
13847
  async function getMachineUserToken(options) {
13848
+ const name = await loadMachineUserName({
13849
+ machineUser: options.name,
13850
+ profile: options.profile
13851
+ });
13852
+ if (!name) throw new Error("Machine user is required. Provide the NAME positional argument, set TAILOR_PLATFORM_MACHINE_USER_NAME, or set a profile default with 'tailor-sdk profile update <profile> --machine-user <name>'.");
13461
13853
  const client = await initOperatorClient(await loadAccessToken({ profile: options.profile }));
13462
13854
  const workspaceId = await loadWorkspaceId({
13463
13855
  workspaceId: options.workspaceId,
@@ -13472,9 +13864,9 @@ async function getMachineUserToken(options) {
13472
13864
  const { machineUser } = await client.getAuthMachineUser({
13473
13865
  workspaceId,
13474
13866
  authNamespace: application.authNamespace,
13475
- name: options.name
13867
+ name
13476
13868
  });
13477
- if (!machineUser) throw new Error(`Machine user ${options.name} not found.`);
13869
+ if (!machineUser) throw new Error(`Machine user ${name} not found.`);
13478
13870
  const resp = await fetchMachineUserToken(application.url, machineUser.clientId, machineUser.clientSecret);
13479
13871
  const expiresAt = /* @__PURE__ */ new Date();
13480
13872
  expiresAt.setSeconds(expiresAt.getSeconds() + resp.expires_in);
@@ -13489,9 +13881,10 @@ const tokenCommand = defineAppCommand({
13489
13881
  description: "Get an access token for a machine user.",
13490
13882
  args: z.object({
13491
13883
  ...deploymentArgs,
13492
- name: arg(z.string(), {
13884
+ name: arg(z.string().optional(), {
13493
13885
  positional: true,
13494
- description: "Machine user name"
13886
+ description: "Machine user name. Falls back to the active profile's default machine user.",
13887
+ env: "TAILOR_PLATFORM_MACHINE_USER_NAME"
13495
13888
  })
13496
13889
  }).strict(),
13497
13890
  run: async (args) => {
@@ -14486,13 +14879,13 @@ function extractBreakingChangeFields(diff) {
14486
14879
  const optionalToRequired = /* @__PURE__ */ new Map();
14487
14880
  const addedRequiredFields = /* @__PURE__ */ new Map();
14488
14881
  const enumValueChanges = /* @__PURE__ */ new Map();
14489
- for (const change of diff.changes) if (change.kind === "field_modified" && change.fieldName) {
14882
+ for (const change of diff.changes) if (change.kind === "field_modified") {
14490
14883
  const { before, after } = change;
14491
- if (before && after && !before.required && after.required) {
14884
+ if (!before.required && after.required) {
14492
14885
  if (!optionalToRequired.has(change.typeName)) optionalToRequired.set(change.typeName, /* @__PURE__ */ new Set());
14493
14886
  assertDefined(optionalToRequired.get(change.typeName), "optionalToRequired entry missing").add(change.fieldName);
14494
14887
  }
14495
- if (before && after && before.type === "enum" && after.type === "enum" && before.allowedValues && after.allowedValues) {
14888
+ if (before.type === "enum" && after.type === "enum" && before.allowedValues && after.allowedValues) {
14496
14889
  const beforeValues = before.allowedValues.map((v) => v.value);
14497
14890
  const afterValues = after.allowedValues.map((v) => v.value);
14498
14891
  const beforeSet = new Set(beforeValues);
@@ -14505,9 +14898,9 @@ function extractBreakingChangeFields(diff) {
14505
14898
  });
14506
14899
  }
14507
14900
  }
14508
- } else if (change.kind === "field_added" && change.fieldName) {
14901
+ } else if (change.kind === "field_added") {
14509
14902
  const { after } = change;
14510
- if (after && after.required) {
14903
+ if (after.required) {
14511
14904
  if (!addedRequiredFields.has(change.typeName)) addedRequiredFields.set(change.typeName, /* @__PURE__ */ new Map());
14512
14905
  assertDefined(addedRequiredFields.get(change.typeName), "addedRequiredFields entry missing").set(change.fieldName, after);
14513
14906
  }
@@ -14991,7 +15384,7 @@ async function generate(options) {
14991
15384
  if (options.init) await handleInitOption(namespacesWithMigrations, options.yes);
14992
15385
  let pluginManager;
14993
15386
  if (plugins.length > 0) pluginManager = new PluginManager(plugins);
14994
- const { defineApplication } = await import("./application-DSXntqnV.mjs");
15387
+ const { defineApplication } = await import("./application-av2raLs6.mjs");
14995
15388
  const application = defineApplication({
14996
15389
  config,
14997
15390
  pluginManager
@@ -15008,10 +15401,7 @@ async function generate(options) {
15008
15401
  await tailordbService.processNamespacePlugins();
15009
15402
  const localTypesObj = tailordbService.types;
15010
15403
  const currentSnapshot = createSnapshotFromLocalTypes(localTypesObj, namespace);
15011
- let previousSnapshot = null;
15012
- try {
15013
- previousSnapshot = reconstructSnapshotFromMigrations(migrationsDir);
15014
- } catch {}
15404
+ const previousSnapshot = reconstructSnapshotFromMigrations(migrationsDir);
15015
15405
  if (!previousSnapshot) await generateInitialSnapshot(currentSnapshot, migrationsDir);
15016
15406
  else await generateDiffFromSnapshot(previousSnapshot, currentSnapshot, migrationsDir, options);
15017
15407
  }
@@ -16577,7 +16967,7 @@ const queryBaseOptionsSchema = z.object({
16577
16967
  profile: z.string().optional(),
16578
16968
  configPath: z.string().optional(),
16579
16969
  engine: queryEngineSchema,
16580
- machineUser: z.string()
16970
+ machineUser: z.string().optional()
16581
16971
  });
16582
16972
  const queryOptionsSchema = queryBaseOptionsSchema.extend({ query: z.string() });
16583
16973
  async function getNamespaceFromSqlQuery(workspaceId, query, client, namespaces) {
@@ -16600,6 +16990,11 @@ async function getNamespaceFromSqlQuery(workspaceId, query, client, namespaces)
16600
16990
  async function loadOptions(options) {
16601
16991
  const result = queryBaseOptionsSchema.safeParse(options);
16602
16992
  if (!result.success) throw new Error(assertDefined(result.error.issues[0], "validation error missing issues").message);
16993
+ const machineUser = await loadMachineUserName({
16994
+ machineUser: result.data.machineUser,
16995
+ profile: result.data.profile
16996
+ });
16997
+ if (!machineUser) throw new Error("Machine user is required. Specify --machine-user, set TAILOR_PLATFORM_MACHINE_USER_NAME, or set a profile default with 'tailor-sdk profile update <profile> --machine-user <name>'.");
16603
16998
  const client = await initOperatorClient(await loadAccessToken({ profile: result.data.profile }));
16604
16999
  const workspaceId = await loadWorkspaceId({
16605
17000
  workspaceId: result.data.workspaceId,
@@ -16615,9 +17010,9 @@ async function loadOptions(options) {
16615
17010
  const { machineUser: machineUserResource } = await client.getAuthMachineUser({
16616
17011
  workspaceId,
16617
17012
  authNamespace: application.authNamespace,
16618
- name: result.data.machineUser
17013
+ name: machineUser
16619
17014
  });
16620
- if (!machineUserResource) throw new Error(`Machine user ${result.data.machineUser} not found.`);
17015
+ if (!machineUserResource) throw new Error(`Machine user ${machineUser} not found.`);
16621
17016
  return {
16622
17017
  engine: result.data.engine,
16623
17018
  client,
@@ -16767,7 +17162,7 @@ async function prepareQueryExecutor(options) {
16767
17162
  error,
16768
17163
  engine,
16769
17164
  namespace,
16770
- machineUser: options.machineUser
17165
+ machineUser: machineUserResource.name
16771
17166
  });
16772
17167
  }
16773
17168
  };
@@ -16981,10 +17376,10 @@ const queryCommand = defineAppCommand({
16981
17376
  description: "Read query string from file; omit to start REPL mode"
16982
17377
  }),
16983
17378
  edit: arg(z.boolean().default(false), { description: "Open a temporary file in your editor; omit to start REPL mode" }),
16984
- "machine-user": arg(z.string(), {
17379
+ "machine-user": arg(z.string().optional(), {
16985
17380
  alias: "m",
16986
17381
  hiddenAlias: "machineuser",
16987
- description: "Machine user name for query execution",
17382
+ description: "Machine user name for query execution. Falls back to the active profile's default machine user.",
16988
17383
  env: "TAILOR_PLATFORM_MACHINE_USER_NAME"
16989
17384
  }),
16990
17385
  "newline-on-enter": arg(z.boolean().optional(), { description: "REPL: when true, Enter inserts a newline and Shift+Enter submits. Use --no-newline-on-enter to swap." })
@@ -17150,4 +17545,4 @@ function isDeno() {
17150
17545
 
17151
17546
  //#endregion
17152
17547
  export { listCommand$5 as $, INITIAL_SCHEMA_NUMBER as $t, truncate as A, commonArgs as An, startCommand as At, logBetaWarning as B, getExecutor as Bt, listCommand$2 as C, PluginManager as Cn, triggerExecutor as Ct, resumeWorkflow as D, apiCall as Dn, jobsCommand as Dt, resumeCommand as E, apiCommand as En, getExecutorJob as Et, writeDbTypesFile as F, pagedLogArgs as Fn, getWorkflowExecution as Ft, organizationTree as G, MIGRATION_LABEL_KEY as Gt, removeCommand$1 as H, executeScript as Ht, getConfiguredEditorCommand as I, paginationArgs as In, listWorkflowExecutions as It, listOrganizations as J, compareSnapshotWithRemote as Jt, treeCommand as K, handleOptionalToRequiredError as Kt, openInConfiguredEditor as L, toPageDirection as Ln, functionExecutionStatusToString as Lt, generate as M, confirmationArgs as Mn, getCommand$5 as Mt, generateCommand as N, deploymentArgs as Nn, getWorkflow as Nt, listCommand$3 as O, assertWritable as On, listExecutorJobs as Ot, generateMigrationScript as P, isVerbose as Pn, executionsCommand as Pt, updateFolder as Q, DIFF_FILE_NAME as Qt, show as R, workspaceArgs as Rn, formatKeyValueTable as Rt, listApps as S, sdkNameLabelKey as Sn, triggerCommand as St, healthCommand as T, prompt as Tn, listExecutors as Tt, updateCommand$1 as U, waitForExecution$1 as Ut, remove as V, deploy as Vt, updateOrganization as W, bundleMigrationScript as Wt, getOrganization as X, protoGqlPermission as Xt, getCommand$1 as Y, generateAllTypeManifestsFromSnapshot as Yt, updateCommand$2 as Z, DB_TYPES_FILE_NAME as Zt, getWorkspace as _, formatMigrationDiff as _n, listFunctionRegistries as _t, updateUser as a, createSnapshotFromLocalTypes as an, createCommand$1 as at, createCommand as b, ensureConfigId as bn, listWebhookExecutors as bt, listCommand as c, getMigrationFilePath as cn, listOAuth2Clients as ct, inviteUser as d, isValidMigrationNumber as dn, getMachineUserToken as dt, MIGRATE_FILE_NAME as en, listFolders as et, restoreCommand as f, loadDiff as fn, tokenCommand as ft, getCommand as g, formatDiffSummary as gn, listCommand$8 as gt, listWorkspaces as h, parseMigrationNumberArg as hn, generate$1 as ht, updateCommand as i, compareSnapshots as in, deleteFolder as it, truncateCommand as j, configArg as jn, startWorkflow as jt, listWorkflows as k, defineAppCommand as kn, watchExecutorJob as kt, listUsers as l, getMigrationFiles as ln, getCommand$3 as lt, listCommand$1 as m, formatMigrationNumber as mn, listMachineUsers as mt, query as n, assertValidMigrationFiles as nn, getFolder as nt, removeCommand as o, getLatestMigrationNumber as on, createFolder as ot, restoreWorkspace as p, reconstructSnapshotFromMigrations as pn, listCommand$7 as pt, listCommand$4 as q, parseMigrationLabelNumber as qt, queryCommand as r, compareLocalTypesWithSnapshot as rn, deleteCommand$1 as rt, removeUser as s, getMigrationDirPath as sn, listCommand$6 as st, isNativeTypeScriptRuntime as t, SCHEMA_FILE_NAME as tn, getCommand$2 as tt, inviteCommand as u, getNextMigrationNumber as un, getOAuth2Client as ut, deleteCommand as v, hasChanges as vn, getCommand$4 as vt, getAppHealth as w, generateUserTypes as wn, listCommand$9 as wt, createWorkspace as x, resourceTrn as xn, webhookCommand as xt, deleteWorkspace as y, getNamespacesWithMigrations as yn, getFunctionRegistry as yt, showCommand as z, getCommand$6 as zt };
17153
- //# sourceMappingURL=runtime-CW3jcQCc.mjs.map
17548
+ //# sourceMappingURL=runtime-C7qTBDD2.mjs.map