siteplane 0.1.40 → 0.1.42

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.
@@ -1286,6 +1286,8 @@ var CONTINUE_SITE_SETUP_LOCATOR_HINT_MAX_BYTES = 512;
1286
1286
  var CONTINUE_SITE_SETUP_REQUESTED_LABEL_MAX_BYTES = 120;
1287
1287
  var CONTINUE_SITE_SETUP_REQUESTED_SECTION_MAX_BYTES = 120;
1288
1288
  var CONTINUE_SITE_SETUP_REQUESTED_SUBSECTION_MAX_BYTES = 120;
1289
+ var SITE_SETUP_OWNER_EDITABILITY_NOTE_MAX_LENGTH = 2e3;
1290
+ var SITE_SETUP_OWNER_EDITABILITY_NOTE_MAX_BYTES = 8e3;
1289
1291
  var CONTINUE_SITE_SETUP_ITEMS_MAX_BYTES = 32 * 1024;
1290
1292
  var CONTINUE_SITE_SETUP_HTTP_BODY_MAX_BYTES = 64 * 1024;
1291
1293
  var siteSetupRunStatusSchema = z14.enum(SITE_SETUP_RUN_STATUSES);
@@ -1375,6 +1377,7 @@ var editorDefinitionV1Schema = z14.object({
1375
1377
  }
1376
1378
  });
1377
1379
  var forbiddenControlOrBidi = /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/u;
1380
+ var forbiddenOwnerNoteControlOrBidi = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/u;
1378
1381
  var unsafeLocator = /<\/?[a-z][^>]*>|\b(?:javascript|data:text\/html)\s*:|\bon[a-z]+\s*=/iu;
1379
1382
  var renderedPathSchema = z14.string().trim().transform((value) => value !== "/" ? value.replace(/\/+$/u, "") : value).superRefine((value, context) => {
1380
1383
  if (!value.startsWith("/") || value === "$global" || value.includes("?") || value.includes("#")) {
@@ -1427,6 +1430,175 @@ var setupCorrectionItemsSchema = z14.array(setupCorrectionItemSchema).max(CONTIN
1427
1430
  });
1428
1431
  }
1429
1432
  });
1433
+ var siteSetupOwnerEditabilityNoteSchema = z14.string().max(SITE_SETUP_OWNER_EDITABILITY_NOTE_MAX_LENGTH).superRefine((value, context) => {
1434
+ if (utf8Bytes(value) > SITE_SETUP_OWNER_EDITABILITY_NOTE_MAX_BYTES) {
1435
+ context.addIssue({
1436
+ code: "custom",
1437
+ message: `ownerEditabilityNote exceeds ${SITE_SETUP_OWNER_EDITABILITY_NOTE_MAX_BYTES} UTF-8 bytes.`
1438
+ });
1439
+ }
1440
+ if (forbiddenOwnerNoteControlOrBidi.test(value)) {
1441
+ context.addIssue({
1442
+ code: "custom",
1443
+ message: "ownerEditabilityNote contains a forbidden control or bidi character."
1444
+ });
1445
+ }
1446
+ });
1447
+ var SITE_SETUP_MODULE_SCOPES = {
1448
+ editing: ["setup:read", "setup:write"],
1449
+ analytics: [
1450
+ "analytics:setup",
1451
+ "analytics:sync",
1452
+ "analytics:test",
1453
+ "analytics:readiness",
1454
+ "analytics:agent_instructions",
1455
+ "analytics:public_key_read"
1456
+ ]
1457
+ };
1458
+ var siteSetupModulesSchema = z14.array(z14.enum(["editing", "analytics"])).min(1).max(2).refine((modules) => modules[0] === "editing" && (modules.length === 1 || modules[1] === "analytics"), "Choose Editing with optional Analytics.");
1459
+ function siteSetupScopes(modules) {
1460
+ return modules.flatMap((module) => [...SITE_SETUP_MODULE_SCOPES[module]]);
1461
+ }
1462
+ function hasExactSiteSetupScopes(scopes, modules) {
1463
+ const matches = (expected) => scopes.length === expected.length && expected.every((scope) => scopes.includes(scope));
1464
+ return modules ? matches(siteSetupScopes(modules)) : matches(siteSetupScopes(["editing"])) || matches(siteSetupScopes(["editing", "analytics"]));
1465
+ }
1466
+ var siteSetupActivityInputSchema = z14.object({
1467
+ phase: z14.enum([
1468
+ "inspecting",
1469
+ "integrating",
1470
+ "deploying",
1471
+ "verifying",
1472
+ "repairing"
1473
+ ]),
1474
+ textId: z14.enum([
1475
+ "inspecting",
1476
+ "integrating",
1477
+ "deploying",
1478
+ "verifying",
1479
+ "repairing"
1480
+ ])
1481
+ }).strict().refine((value) => value.phase === value.textId, "Activity text must describe its phase.");
1482
+ var nextActionFields = {
1483
+ actor: z14.enum(["agent", "user", "siteplane"]),
1484
+ boundary: z14.enum([
1485
+ "source",
1486
+ "environment",
1487
+ "deployment",
1488
+ "verification",
1489
+ "authorization",
1490
+ "review"
1491
+ ]),
1492
+ precondition: z14.string().min(1).max(1e3),
1493
+ instruction: z14.string().min(1).max(2e3),
1494
+ expectedEvidence: z14.string().min(1).max(1e3)
1495
+ };
1496
+ var siteSetupNextActionSchema = z14.discriminatedUnion("kind", [
1497
+ z14.object({
1498
+ ...nextActionFields,
1499
+ kind: z14.literal("run_command"),
1500
+ command: z14.string().min(1).max(500)
1501
+ }).strict(),
1502
+ z14.object({ ...nextActionFields, kind: z14.literal("agent_edit") }).strict(),
1503
+ z14.object({ ...nextActionFields, kind: z14.literal("needs_user_action") }).strict(),
1504
+ z14.object({ ...nextActionFields, kind: z14.literal("wait") }).strict(),
1505
+ z14.object({ ...nextActionFields, kind: z14.literal("done") }).strict()
1506
+ ]);
1507
+ var siteSetupTaskRunSchema = z14.object({
1508
+ runId: z14.string().uuid(),
1509
+ mode: siteSetupRunModeSchema,
1510
+ status: siteSetupRunStatusSchema,
1511
+ fieldContractHash: z14.string().nullable(),
1512
+ deploymentOrigin: z14.string().url().nullable(),
1513
+ deploymentRevision: z14.string().nullable(),
1514
+ publicRuntimeKeyId: z14.string().uuid().nullable(),
1515
+ reviewVersion: z14.string().nullable()
1516
+ }).strict();
1517
+ var siteSetupTaskProgressSchema = z14.object({
1518
+ progressStage: z14.enum([
1519
+ "waiting_for_connection",
1520
+ "agent_connected",
1521
+ "project_context_loaded",
1522
+ "fields_prepared",
1523
+ "deployment_verification",
1524
+ "ready_for_review",
1525
+ "action_required",
1526
+ "completed"
1527
+ ]),
1528
+ lastVerifiedAt: z14.string().datetime().nullable(),
1529
+ lastActivityAt: z14.string().datetime(),
1530
+ activitySource: z14.enum(["user", "server", "agent"]),
1531
+ activityPhase: siteSetupActivityInputSchema.shape.phase.nullable(),
1532
+ activityTextId: siteSetupActivityInputSchema.shape.textId.nullable()
1533
+ }).strict();
1534
+ var siteSetupTaskSchema = z14.object({
1535
+ contractVersion: z14.literal("siteplane.setup-task.v2"),
1536
+ workflow: z14.enum(["initial_setup", "structure_update"]),
1537
+ goal: z14.string().min(1),
1538
+ modules: siteSetupModulesSchema,
1539
+ authorizationVersion: z14.number().int().positive(),
1540
+ authorizedScopes: z14.array(z14.string()).min(2),
1541
+ site: z14.object({
1542
+ siteId: z14.string().uuid(),
1543
+ portalPath: z14.string(),
1544
+ adminOrigin: z14.string().url()
1545
+ }).strict().nullable(),
1546
+ run: siteSetupTaskRunSchema.nullable(),
1547
+ progress: siteSetupTaskProgressSchema.nullable(),
1548
+ assignment: z14.literal("owned"),
1549
+ deadline: z14.string().datetime().nullable(),
1550
+ userInstructions: z14.object({
1551
+ text: siteSetupOwnerEditabilityNoteSchema,
1552
+ source: z14.literal("user"),
1553
+ trust: z14.literal("untrusted")
1554
+ }).strict(),
1555
+ corrections: setupCorrectionItemsSchema,
1556
+ environmentBindings: z14.array(z14.object({
1557
+ name: z14.string().regex(/^[A-Z][A-Z0-9_]+$/u),
1558
+ source: z14.string().min(1),
1559
+ sensitivity: z14.enum(["public", "secret"]),
1560
+ usage: z14.enum(["build", "server", "build_and_server"]),
1561
+ evidence: z14.string().min(1)
1562
+ }).strict()),
1563
+ nextAction: siteSetupNextActionSchema,
1564
+ error: z14.object({
1565
+ code: z14.string().regex(/^[a-z0-9_.]+$/u).max(160),
1566
+ boundary: nextActionFields.boundary,
1567
+ responsibleActor: nextActionFields.actor,
1568
+ retryable: z14.boolean(),
1569
+ retryAfter: z14.number().int().nonnegative().nullable(),
1570
+ requestId: z14.string().regex(/^[A-Za-z0-9_-]+$/u).max(128)
1571
+ }).strict().nullable(),
1572
+ packages: z14.object({
1573
+ siteplane: z14.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u),
1574
+ runtimeNext: z14.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u)
1575
+ }).strict(),
1576
+ communication: z14.object({
1577
+ beforeSourceChanges: z14.string().min(1),
1578
+ updates: z14.array(z14.string().min(1)).min(1),
1579
+ blocker: z14.string().min(1)
1580
+ }).strict(),
1581
+ discovery: z14.object({
1582
+ inspectPublicRoutes: z14.boolean(),
1583
+ contentKinds: z14.array(z14.enum(["text", "longText", "link", "image"])).min(1),
1584
+ rules: z14.array(z14.string().min(1)).min(1)
1585
+ }).strict(),
1586
+ steps: z14.array(z14.object({
1587
+ id: z14.enum([
1588
+ "inspect_repository",
1589
+ "install_packages",
1590
+ "instrument_fields",
1591
+ "apply_contract",
1592
+ "deploy_production",
1593
+ "verify_deployment"
1594
+ ]),
1595
+ instruction: z14.string().min(1)
1596
+ }).strict()).length(6),
1597
+ completion: z14.object({
1598
+ verifiedStatus: z14.literal("ready_for_review"),
1599
+ instruction: z14.string().min(1)
1600
+ }).strict()
1601
+ }).strict().refine((task) => hasExactSiteSetupScopes(task.authorizedScopes, task.modules), "Task scopes must exactly match its modules.");
1430
1602
  var canonicalHashSchema = z14.string().regex(/^sha256:[0-9a-f]{64}$/iu);
1431
1603
  var deploymentRevisionSchema = normalizedSafeTextSchema(256, "deploymentRevision");
1432
1604
  var continueSiteSetupInputSchema = z14.object({
@@ -1434,7 +1606,15 @@ var continueSiteSetupInputSchema = z14.object({
1434
1606
  runId: z14.string().uuid(),
1435
1607
  expectedFieldContractHash: canonicalHashSchema,
1436
1608
  expectedDeploymentRevision: deploymentRevisionSchema,
1437
- correctionItems: setupCorrectionItemsSchema
1609
+ correctionItems: setupCorrectionItemsSchema,
1610
+ ownerEditabilityNote: siteSetupOwnerEditabilityNoteSchema.optional()
1611
+ }).strict();
1612
+ var saveSiteSetupOwnerNoteInputSchema = z14.object({
1613
+ siteId: z14.string().uuid(),
1614
+ runId: z14.string().uuid(),
1615
+ expectedFieldContractHash: canonicalHashSchema,
1616
+ expectedDeploymentRevision: deploymentRevisionSchema,
1617
+ ownerEditabilityNote: siteSetupOwnerEditabilityNoteSchema
1438
1618
  }).strict();
1439
1619
  var siteSetupContextInputSchema = z14.object({}).strict();
1440
1620
  var siteSetupApplyInputSchema = z14.object({
@@ -1599,6 +1779,7 @@ var FIELD_BRIDGE_MESSAGE_TYPES = [
1599
1779
  "siteplane:field-bridge:preview-ack",
1600
1780
  "siteplane:field-bridge:set-visual-control-state",
1601
1781
  "siteplane:field-bridge:missing-content",
1782
+ "siteplane:field-bridge:preview-scrolled",
1602
1783
  "siteplane:field-bridge:error"
1603
1784
  ];
1604
1785
  var canonicalFieldContractHashSchema = z15.string().regex(/^sha256:[0-9a-f]{64}$/u);
@@ -1729,6 +1910,10 @@ var fieldBridgeMissingContentMessageSchema = fieldBridgeBaseSchema.extend({
1729
1910
  suggestedSection: bridgeSectionSchema.optional()
1730
1911
  }).strict()
1731
1912
  });
1913
+ var fieldBridgePreviewScrolledMessageSchema = fieldBridgeBaseSchema.extend({
1914
+ type: z15.literal("siteplane:field-bridge:preview-scrolled"),
1915
+ payload: z15.object({ renderedPath: realRenderedPathSchema }).strict()
1916
+ });
1732
1917
  var fieldBridgeErrorMessageSchema = fieldBridgeBaseSchema.extend({
1733
1918
  type: z15.literal("siteplane:field-bridge:error"),
1734
1919
  payload: z15.object({
@@ -1748,6 +1933,7 @@ var fieldBridgeMessageSchema = z15.discriminatedUnion("type", [
1748
1933
  fieldBridgePreviewAckMessageSchema,
1749
1934
  fieldBridgeSetVisualControlStateMessageSchema,
1750
1935
  fieldBridgeMissingContentMessageSchema,
1936
+ fieldBridgePreviewScrolledMessageSchema,
1751
1937
  fieldBridgeErrorMessageSchema
1752
1938
  ]);
1753
1939
 
@@ -2920,49 +3106,54 @@ async function bookingTestCommand(input) {
2920
3106
  });
2921
3107
  }
2922
3108
 
2923
- // ../cli/dist/commands/connect.js
2924
- import { spawn } from "child_process";
2925
- import { randomBytes } from "crypto";
2926
- import { z as z27 } from "zod";
2927
-
2928
- // ../cli/dist/config/credentials.js
2929
- import { execFile } from "child_process";
3109
+ // ../cli/dist/config/project-config.js
3110
+ import { access, chmod, open, readFile as readFile5, rename, rm } from "fs/promises";
2930
3111
  import { randomUUID as randomUUID2 } from "crypto";
2931
- import { chmod, mkdir as mkdir5, open, readFile as readFile5, rename, rm } from "fs/promises";
2932
- import { dirname as dirname5, join as join3, relative } from "path";
2933
- import { promisify } from "util";
3112
+ import { join as join3 } from "path";
2934
3113
  import { z as z24 } from "zod";
2935
- var siteplaneCredentialsSchema = z24.object({
2936
- accessToken: z24.string().trim().min(1),
2937
- siteRevalidationSecret: z24.string().trim().min(1)
3114
+ var siteplaneProjectConfigSchema = z24.object({
3115
+ version: z24.literal(1),
3116
+ apiBaseUrl: z24.string().url(),
3117
+ siteId: z24.string().uuid(),
3118
+ publicSiteKeyId: z24.string().uuid(),
3119
+ publicSiteKey: z24.string().trim().min(1),
3120
+ fieldContractHash: z24.string().regex(/^sha256:[0-9a-f]{64}$/iu).optional()
2938
3121
  }).strict();
2939
- async function assertLocalCredentialsPathSafe(projectDir, options = {}) {
2940
- const path = join3(projectDir, ".siteplane/credentials.json");
2941
- const isTrackedFile = options.isTrackedFile ?? ((targetPath) => gitPathMatches(projectDir, targetPath, "ls-files"));
2942
- const isIgnoredFile = options.isIgnoredFile ?? ((targetPath) => gitPathMatches(projectDir, targetPath, "check-ignore"));
2943
- if (await isTrackedFile(path)) {
2944
- throw new Error("Refusing to write Siteplane credentials into a tracked file.");
3122
+ async function readProjectPackageJson(projectDir) {
3123
+ return JSON.parse(await readFile5(join3(projectDir, "package.json"), "utf8"));
3124
+ }
3125
+ async function detectNextProject(projectDir) {
3126
+ const packageJson = await readProjectPackageJson(projectDir).catch(() => null);
3127
+ if (packageJson?.dependencies?.next || packageJson?.devDependencies?.next) {
3128
+ return true;
2945
3129
  }
2946
- if (!await isIgnoredFile(path)) {
2947
- throw new Error("Add .siteplane/credentials.json to .gitignore before running Siteplane connect.");
3130
+ for (const fileName of [
3131
+ "next.config.js",
3132
+ "next.config.mjs",
3133
+ "next.config.ts"
3134
+ ]) {
3135
+ try {
3136
+ await access(join3(projectDir, fileName));
3137
+ return true;
3138
+ } catch {
3139
+ }
2948
3140
  }
2949
- return path;
3141
+ return false;
2950
3142
  }
2951
- async function writeLocalCredentials(projectDir, credentials, options = {}) {
2952
- const path = await assertLocalCredentialsPathSafe(projectDir, options);
2953
- const parsed = siteplaneCredentialsSchema.parse(credentials);
2954
- await mkdir5(dirname5(path), { recursive: true, mode: 448 });
2955
- await writeCredentialsAtomically(path, parsed);
3143
+ async function writeProjectConfig(projectDir, config) {
3144
+ const path = join3(projectDir, "siteplane.config.json");
3145
+ const parsed = siteplaneProjectConfigSchema.parse(config);
3146
+ await writeJsonAtomically(path, parsed, 420);
2956
3147
  return path;
2957
3148
  }
2958
- async function readLocalCredentials(projectDir) {
2959
- return siteplaneCredentialsSchema.parse(JSON.parse(await readFile5(join3(projectDir, ".siteplane/credentials.json"), "utf8")));
3149
+ async function readProjectConfig(projectDir) {
3150
+ return siteplaneProjectConfigSchema.parse(JSON.parse(await readFile5(join3(projectDir, "siteplane.config.json"), "utf8")));
2960
3151
  }
2961
- async function writeCredentialsAtomically(path, credentials) {
3152
+ async function writeJsonAtomically(path, value, mode) {
2962
3153
  const temporaryPath = `${path}.${randomUUID2()}.tmp`;
2963
- const file = await open(temporaryPath, "wx", 384);
3154
+ const file = await open(temporaryPath, "wx", mode);
2964
3155
  try {
2965
- await file.writeFile(`${JSON.stringify(credentials, null, 2)}
3156
+ await file.writeFile(`${JSON.stringify(value, null, 2)}
2966
3157
  `, "utf8");
2967
3158
  await file.sync();
2968
3159
  } catch (error) {
@@ -2973,71 +3164,51 @@ async function writeCredentialsAtomically(path, credentials) {
2973
3164
  await file.close();
2974
3165
  try {
2975
3166
  await rename(temporaryPath, path);
2976
- await chmod(path, 384);
3167
+ await chmod(path, mode);
2977
3168
  } catch (error) {
2978
3169
  await rm(temporaryPath, { force: true });
2979
3170
  throw error;
2980
3171
  }
2981
3172
  }
2982
- var execFileAsync = promisify(execFile);
2983
- async function gitPathMatches(projectDir, path, command) {
2984
- const args = command === "check-ignore" ? ["check-ignore", "--quiet", relative(projectDir, path)] : ["ls-files", "--error-unmatch", relative(projectDir, path)];
2985
- try {
2986
- await execFileAsync("git", args, { cwd: projectDir });
2987
- return true;
2988
- } catch {
2989
- return false;
2990
- }
2991
- }
2992
3173
 
2993
- // ../cli/dist/config/project-config.js
2994
- import { access, chmod as chmod2, open as open2, readFile as readFile6, rename as rename2, rm as rm2 } from "fs/promises";
3174
+ // ../cli/dist/config/credentials.js
3175
+ import { execFile } from "child_process";
2995
3176
  import { randomUUID as randomUUID3 } from "crypto";
2996
- import { join as join4 } from "path";
3177
+ import { chmod as chmod2, mkdir as mkdir5, open as open2, readFile as readFile6, rename as rename2, rm as rm2 } from "fs/promises";
3178
+ import { dirname as dirname5, join as join4, relative } from "path";
3179
+ import { promisify } from "util";
2997
3180
  import { z as z25 } from "zod";
2998
- var siteplaneProjectConfigSchema = z25.object({
2999
- version: z25.literal(1),
3000
- apiBaseUrl: z25.string().url(),
3001
- siteId: z25.string().uuid(),
3002
- publicSiteKeyId: z25.string().uuid(),
3003
- publicSiteKey: z25.string().trim().min(1),
3004
- fieldContractHash: z25.string().regex(/^sha256:[0-9a-f]{64}$/iu).optional()
3181
+ var siteplaneCredentialsSchema = z25.object({
3182
+ accessToken: z25.string().trim().min(1),
3183
+ siteRevalidationSecret: z25.string().trim().min(1)
3005
3184
  }).strict();
3006
- async function readProjectPackageJson(projectDir) {
3007
- return JSON.parse(await readFile6(join4(projectDir, "package.json"), "utf8"));
3008
- }
3009
- async function detectNextProject(projectDir) {
3010
- const packageJson = await readProjectPackageJson(projectDir).catch(() => null);
3011
- if (packageJson?.dependencies?.next || packageJson?.devDependencies?.next) {
3012
- return true;
3185
+ async function assertLocalCredentialsPathSafe(projectDir, options = {}) {
3186
+ const path = join4(projectDir, ".siteplane/credentials.json");
3187
+ const isTrackedFile = options.isTrackedFile ?? ((targetPath) => gitPathMatches(projectDir, targetPath, "ls-files"));
3188
+ const isIgnoredFile = options.isIgnoredFile ?? ((targetPath) => gitPathMatches(projectDir, targetPath, "check-ignore"));
3189
+ if (await isTrackedFile(path)) {
3190
+ throw new Error("Refusing to write Siteplane credentials into a tracked file.");
3013
3191
  }
3014
- for (const fileName of [
3015
- "next.config.js",
3016
- "next.config.mjs",
3017
- "next.config.ts"
3018
- ]) {
3019
- try {
3020
- await access(join4(projectDir, fileName));
3021
- return true;
3022
- } catch {
3023
- }
3192
+ if (!await isIgnoredFile(path)) {
3193
+ throw new Error("Add .siteplane/credentials.json to .gitignore before running Siteplane init.");
3024
3194
  }
3025
- return false;
3195
+ return path;
3026
3196
  }
3027
- async function writeProjectConfig(projectDir, config) {
3028
- const path = join4(projectDir, "siteplane.config.json");
3029
- const parsed = siteplaneProjectConfigSchema.parse(config);
3030
- await writeJsonAtomically(path, parsed, 420);
3197
+ async function writeLocalCredentials(projectDir, credentials, options = {}) {
3198
+ const path = await assertLocalCredentialsPathSafe(projectDir, options);
3199
+ const parsed = siteplaneCredentialsSchema.parse(credentials);
3200
+ await mkdir5(dirname5(path), { recursive: true, mode: 448 });
3201
+ await writeCredentialsAtomically(path, parsed);
3031
3202
  return path;
3032
3203
  }
3033
- async function readProjectConfig(projectDir) {
3034
- return siteplaneProjectConfigSchema.parse(JSON.parse(await readFile6(join4(projectDir, "siteplane.config.json"), "utf8")));
3204
+ async function readLocalCredentials(projectDir) {
3205
+ return siteplaneCredentialsSchema.parse(JSON.parse(await readFile6(join4(projectDir, ".siteplane/credentials.json"), "utf8")));
3035
3206
  }
3036
- async function writeJsonAtomically(path, value, mode) {
3207
+ async function writeCredentialsAtomically(path, credentials) {
3037
3208
  const temporaryPath = `${path}.${randomUUID3()}.tmp`;
3038
- const file = await open2(temporaryPath, "wx", mode);
3209
+ const file = await open2(temporaryPath, "wx", 384);
3039
3210
  try {
3040
- await file.writeFile(`${JSON.stringify(value, null, 2)}
3211
+ await file.writeFile(`${JSON.stringify(credentials, null, 2)}
3041
3212
  `, "utf8");
3042
3213
  await file.sync();
3043
3214
  } catch (error) {
@@ -3048,12 +3219,22 @@ async function writeJsonAtomically(path, value, mode) {
3048
3219
  await file.close();
3049
3220
  try {
3050
3221
  await rename2(temporaryPath, path);
3051
- await chmod2(path, mode);
3222
+ await chmod2(path, 384);
3052
3223
  } catch (error) {
3053
3224
  await rm2(temporaryPath, { force: true });
3054
3225
  throw error;
3055
3226
  }
3056
3227
  }
3228
+ var execFileAsync = promisify(execFile);
3229
+ async function gitPathMatches(projectDir, path, command) {
3230
+ const args = command === "check-ignore" ? ["check-ignore", "--quiet", relative(projectDir, path)] : ["ls-files", "--error-unmatch", relative(projectDir, path)];
3231
+ try {
3232
+ await execFileAsync("git", args, { cwd: projectDir });
3233
+ return true;
3234
+ } catch {
3235
+ return false;
3236
+ }
3237
+ }
3057
3238
 
3058
3239
  // ../cli/dist/commands/init.js
3059
3240
  import { join as join5 } from "path";
@@ -3071,9 +3252,9 @@ async function initCommand(input) {
3071
3252
  return {
3072
3253
  ...paths,
3073
3254
  nextSteps: [
3074
- "npx siteplane setup context",
3075
- "Instrument the site and create EditorDefinitionV1.",
3076
- "npx siteplane setup apply --definition /tmp/siteplane-editor.json"
3255
+ "Run npx siteplane setup context and read the returned task.",
3256
+ "Before source changes, briefly tell the user what Siteplane requested and what you will do.",
3257
+ "Follow the returned steps through setup verify and stop only at ready_for_review or action_required."
3077
3258
  ]
3078
3259
  };
3079
3260
  }
@@ -3192,149 +3373,6 @@ function readErrorMessage(payload) {
3192
3373
  return null;
3193
3374
  }
3194
3375
 
3195
- // ../cli/dist/commands/connect.js
3196
- var claimResponseSchema = z27.object({
3197
- ok: z27.literal(true),
3198
- data: z27.object({
3199
- pairingId: z27.string().uuid(),
3200
- status: z27.literal("approval_required"),
3201
- approvalUrl: z27.string().url()
3202
- }).passthrough()
3203
- }).strict();
3204
- var waitingResponseSchema = z27.object({
3205
- ok: z27.literal(true),
3206
- data: z27.object({ status: z27.literal("approval_required") }).strict()
3207
- }).strict();
3208
- var bootstrapResponseSchema2 = z27.object({
3209
- ok: z27.literal(true),
3210
- data: siteSetupBootstrapDataSchema
3211
- }).strict();
3212
- async function connectCommand(input) {
3213
- if (!await detectNextProject(input.projectDir)) {
3214
- throw new Error("Siteplane connect currently supports Next.js projects.");
3215
- }
3216
- await assertLocalCredentialsPathSafe(input.projectDir, {
3217
- ...input.isIgnoredFile ? { isIgnoredFile: input.isIgnoredFile } : {},
3218
- ...input.isTrackedFile ? { isTrackedFile: input.isTrackedFile } : {}
3219
- });
3220
- const fetcher = input.fetcher ?? fetch;
3221
- const pollSecret = randomBytes(32).toString("base64url");
3222
- const envelopeKey = randomBytes(32).toString("base64url");
3223
- const endpoint = `${input.apiBaseUrl.replace(/\/$/, "")}/api/cli/connect`;
3224
- const headers = createHeaders(input);
3225
- const claimResponse = await fetcher(endpoint, {
3226
- method: "POST",
3227
- headers,
3228
- body: JSON.stringify({
3229
- action: "claim",
3230
- pairingCode: input.pairingCode.trim().toUpperCase(),
3231
- pollSecret,
3232
- envelopeKey,
3233
- agentLabel: input.agentLabel?.trim() || null
3234
- })
3235
- });
3236
- const claimPayload = await readJson(claimResponse);
3237
- const claim = claimResponseSchema.safeParse(claimPayload);
3238
- if (!claimResponse.ok || !claim.success) {
3239
- throw new Error(readErrorMessage2(claimPayload) ?? "Siteplane pairing failed.");
3240
- }
3241
- let browserOpened = false;
3242
- try {
3243
- await (input.openBrowser ?? openInDefaultBrowser)(claim.data.data.approvalUrl);
3244
- browserOpened = true;
3245
- } catch {
3246
- }
3247
- input.onApprovalRequired?.({
3248
- approvalUrl: claim.data.data.approvalUrl,
3249
- browserOpened
3250
- });
3251
- const wait = input.wait ?? ((milliseconds) => new Promise((resolve2) => setTimeout(resolve2, milliseconds)));
3252
- let bootstrap = null;
3253
- for (; ; ) {
3254
- const pollResponse = await fetcher(endpoint, {
3255
- method: "POST",
3256
- headers,
3257
- body: JSON.stringify({
3258
- action: "poll",
3259
- pairingId: claim.data.data.pairingId,
3260
- pollSecret,
3261
- envelopeKey
3262
- })
3263
- });
3264
- const pollPayload = await readJson(pollResponse);
3265
- const ready = bootstrapResponseSchema2.safeParse(pollPayload);
3266
- if (pollResponse.ok && ready.success) {
3267
- bootstrap = ready.data.data;
3268
- break;
3269
- }
3270
- if (pollResponse.status !== 202 || !waitingResponseSchema.safeParse(pollPayload).success) {
3271
- throw new Error(readErrorMessage2(pollPayload) ?? "Siteplane pairing was not approved.");
3272
- }
3273
- await wait(1500);
3274
- }
3275
- const paths = await persistSiteSetupBootstrap({
3276
- projectDir: input.projectDir,
3277
- setupToken: "pairing",
3278
- apiBaseUrl: input.apiBaseUrl,
3279
- ...input.isIgnoredFile ? { isIgnoredFile: input.isIgnoredFile } : {},
3280
- ...input.isTrackedFile ? { isTrackedFile: input.isTrackedFile } : {}
3281
- }, bootstrap);
3282
- const acknowledgement = await fetcher(endpoint, {
3283
- method: "POST",
3284
- headers,
3285
- body: JSON.stringify({
3286
- action: "acknowledge",
3287
- pairingId: claim.data.data.pairingId,
3288
- pollSecret,
3289
- envelopeKey
3290
- })
3291
- });
3292
- if (!acknowledgement.ok) {
3293
- throw new Error("Siteplane setup acknowledgement failed.");
3294
- }
3295
- return {
3296
- ...paths,
3297
- nextSteps: [
3298
- "npx siteplane setup context",
3299
- "Instrument the site and create EditorDefinitionV1.",
3300
- "npx siteplane setup apply --definition /tmp/siteplane-editor.json"
3301
- ]
3302
- };
3303
- }
3304
- async function openInDefaultBrowser(url) {
3305
- const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "rundll32.exe" : "xdg-open";
3306
- const args = process.platform === "win32" ? ["url.dll,FileProtocolHandler", url] : [url];
3307
- await new Promise((resolve2, reject) => {
3308
- const child = spawn(command, args, { detached: true, stdio: "ignore" });
3309
- child.once("error", reject);
3310
- child.once("spawn", () => {
3311
- child.unref();
3312
- resolve2();
3313
- });
3314
- });
3315
- }
3316
- function createHeaders(input) {
3317
- return new Headers({
3318
- "content-type": "application/json",
3319
- ...input.vercelAutomationBypassSecret?.trim() ? { "x-vercel-protection-bypass": input.vercelAutomationBypassSecret.trim() } : {}
3320
- });
3321
- }
3322
- async function readJson(response) {
3323
- try {
3324
- return await response.json();
3325
- } catch {
3326
- return null;
3327
- }
3328
- }
3329
- function readErrorMessage2(payload) {
3330
- if (!payload || typeof payload !== "object" || !("error" in payload))
3331
- return null;
3332
- const error = payload.error;
3333
- if (!error || typeof error !== "object" || !("message" in error))
3334
- return null;
3335
- return typeof error.message === "string" ? error.message : null;
3336
- }
3337
-
3338
3376
  // ../cli/dist/commands/scan.js
3339
3377
  import { readdir } from "fs/promises";
3340
3378
  import { extname, join as join6 } from "path";
@@ -3380,7 +3418,7 @@ async function collectSourceFiles(directory) {
3380
3418
  import { execFile as execFile2 } from "child_process";
3381
3419
  import { readFile as readFile7 } from "fs/promises";
3382
3420
  import { promisify as promisify2 } from "util";
3383
- import { z as z28 } from "zod";
3421
+ import { z as z27 } from "zod";
3384
3422
 
3385
3423
  // ../cli/dist/scan/next-source-scan.js
3386
3424
  import ts2 from "typescript";
@@ -4047,52 +4085,30 @@ function isPositionalFieldReference(value) {
4047
4085
 
4048
4086
  // ../cli/dist/commands/site-setup.js
4049
4087
  var execFileAsync2 = promisify2(execFile2);
4050
- var safeErrorSchema = z28.object({
4051
- code: z28.string().trim().min(1),
4052
- message: z28.string().trim().min(1)
4088
+ var safeErrorSchema = z27.object({
4089
+ code: z27.string().trim().min(1),
4090
+ message: z27.string().trim().min(1)
4053
4091
  }).passthrough();
4054
- var errorResponseSchema2 = z28.object({ ok: z28.literal(false), error: safeErrorSchema }).passthrough();
4055
- var contextDataSchema = z28.object({
4056
- site: z28.object({ siteId: z28.string().uuid(), portalPath: z28.string() }),
4057
- run: z28.object({
4058
- runId: z28.string().uuid(),
4059
- mode: z28.enum(["initial", "update"]),
4060
- status: z28.enum([
4061
- "waiting_for_agent",
4062
- "working",
4063
- "action_required",
4064
- "ready_for_review"
4065
- ]),
4066
- fieldContractHash: z28.string().nullable(),
4067
- deploymentOrigin: z28.string().nullable(),
4068
- deploymentRevision: z28.string().nullable(),
4069
- errorCode: z28.string().nullable(),
4070
- errorMessage: z28.string().nullable()
4071
- }),
4072
- structureHandoff: z28.object({
4073
- pendingFields: z28.array(setupCorrectionItemSchema).min(1).max(50)
4074
- }).strict().nullable(),
4075
- allowedTasks: z28.array(z28.string()),
4076
- requiredEnvironmentNames: z28.array(z28.string())
4092
+ var errorResponseSchema2 = z27.object({ ok: z27.literal(false), error: safeErrorSchema }).passthrough();
4093
+ var contextDataSchema = z27.object({ task: siteSetupTaskSchema }).strict();
4094
+ var contextResponseSchema = z27.object({ ok: z27.literal(true), data: contextDataSchema }).strict();
4095
+ var applyDataSchema = z27.object({
4096
+ status: z27.enum(["applied", "ready_for_review"]),
4097
+ runId: z27.string().uuid().optional(),
4098
+ contractVersionId: z27.string().uuid().optional(),
4099
+ fieldContractHash: z27.string().regex(/^sha256:[0-9a-f]{64}$/u),
4100
+ editorDefinitionHash: z27.string().regex(/^sha256:[0-9a-f]{64}$/u).optional(),
4101
+ fieldCount: z27.number().int().nonnegative().optional(),
4102
+ routeCount: z27.number().int().nonnegative().optional()
4077
4103
  }).strict();
4078
- var contextResponseSchema = z28.object({ ok: z28.literal(true), data: contextDataSchema }).strict();
4079
- var applyDataSchema = z28.object({
4080
- status: z28.enum(["applied", "ready_for_review"]),
4081
- runId: z28.string().uuid().optional(),
4082
- contractVersionId: z28.string().uuid().optional(),
4083
- fieldContractHash: z28.string().regex(/^sha256:[0-9a-f]{64}$/u),
4084
- editorDefinitionHash: z28.string().regex(/^sha256:[0-9a-f]{64}$/u).optional(),
4085
- fieldCount: z28.number().int().nonnegative().optional(),
4086
- routeCount: z28.number().int().nonnegative().optional()
4104
+ var applyResponseSchema = z27.object({ ok: z27.literal(true), data: applyDataSchema }).strict();
4105
+ var verifyDataSchema = z27.object({
4106
+ status: z27.literal("ready_for_review"),
4107
+ runId: z27.string().uuid().optional(),
4108
+ deploymentOrigin: z27.string().url().optional(),
4109
+ deploymentRevision: z27.string().optional()
4087
4110
  }).strict();
4088
- var applyResponseSchema = z28.object({ ok: z28.literal(true), data: applyDataSchema }).strict();
4089
- var verifyDataSchema = z28.object({
4090
- status: z28.literal("ready_for_review"),
4091
- runId: z28.string().uuid().optional(),
4092
- deploymentOrigin: z28.string().url().optional(),
4093
- deploymentRevision: z28.string().optional()
4094
- }).strict();
4095
- var verifyResponseSchema = z28.object({ ok: z28.literal(true), data: verifyDataSchema }).strict();
4111
+ var verifyResponseSchema = z27.object({ ok: z27.literal(true), data: verifyDataSchema }).strict();
4096
4112
  async function siteSetupContextCommand(input) {
4097
4113
  const response = await postSiteSetup(input, "context", {});
4098
4114
  const parsed = contextResponseSchema.safeParse(response.payload);
@@ -4212,36 +4228,47 @@ async function readGitRevision(projectDir) {
4212
4228
  }
4213
4229
  return revision;
4214
4230
  }
4231
+ async function siteSetupActivityCommand(input) {
4232
+ const activity = siteSetupActivityInputSchema.safeParse({
4233
+ phase: input.phase,
4234
+ textId: input.phase
4235
+ });
4236
+ if (!activity.success)
4237
+ return {
4238
+ status: "action_required",
4239
+ code: "site_setup.invalid_activity",
4240
+ message: "Choose inspecting, integrating, deploying, verifying or repairing."
4241
+ };
4242
+ const response = await postSiteSetup(input, "activity", activity.data);
4243
+ const parsed = z27.object({
4244
+ ok: z27.literal(true),
4245
+ data: z27.object({ status: z27.enum(["recorded", "rate_limited"]) }).strict()
4246
+ }).strict().safeParse(response.payload);
4247
+ return response.ok && parsed.success ? parsed.data.data : actionRequired(response.payload, "Setup activity could not be recorded.");
4248
+ }
4215
4249
 
4216
4250
  // src/bin/run-siteplane.ts
4217
4251
  async function runSiteplaneCli(args, dependencies = createDefaultDependencies()) {
4218
4252
  const [command, ...commandArgs] = args;
4219
- if (command === "connect") {
4220
- const pairingCode = commandArgs[0];
4221
- if (pairingCode === "--help" || pairingCode === "-h") {
4222
- dependencies.stdout("Usage: siteplane connect <pairing-code>");
4223
- return { exitCode: 0 };
4224
- }
4253
+ if (command === "init") {
4254
+ const setupToken = readOption(commandArgs, "--setup-token");
4225
4255
  const apiBaseUrl = readOption(commandArgs, "--api-base-url") ?? dependencies.env.SITEPLANE_API_BASE_URL ?? "https://siteplane.io";
4226
- if (!pairingCode || pairingCode.startsWith("--")) {
4227
- throw new Error("Usage: siteplane connect <pairing-code>");
4256
+ if (!setupToken) {
4257
+ throw new Error("Usage: siteplane init --setup-token <one-time-grant>");
4228
4258
  }
4229
- const result = await dependencies.commands.connectCommand({
4259
+ const result = await dependencies.commands.initCommand({
4230
4260
  projectDir: dependencies.cwd(),
4231
- pairingCode,
4261
+ setupToken,
4232
4262
  apiBaseUrl,
4233
- onApprovalRequired: ({ approvalUrl, browserOpened }) => {
4234
- dependencies.stdout(
4235
- browserOpened ? "Opened Siteplane in your browser. Approve the connection there:" : "Could not open a browser automatically. Approve the connection here:"
4236
- );
4237
- dependencies.stdout(approvalUrl);
4238
- },
4239
4263
  ...readOptionalVercelAutomationBypassSecret(dependencies.env)
4240
4264
  });
4241
4265
  dependencies.stdout(`Wrote ${result.configPath}`);
4242
4266
  dependencies.stdout(`Wrote ${result.credentialsPath}`);
4243
- dependencies.stdout("Siteplane connected. Next steps:");
4244
- for (const nextStep of result.nextSteps) dependencies.stdout(`- ${nextStep}`);
4267
+ dependencies.stdout(
4268
+ "Siteplane setup connection stored securely. Next steps:"
4269
+ );
4270
+ for (const nextStep of result.nextSteps)
4271
+ dependencies.stdout(`- ${nextStep}`);
4245
4272
  return { exitCode: 0 };
4246
4273
  }
4247
4274
  if (command === "booking") {
@@ -4258,10 +4285,10 @@ async function runSiteplaneCli(args, dependencies = createDefaultDependencies())
4258
4285
  return { exitCode: 0 };
4259
4286
  }
4260
4287
  if (command === "--help" || command === "-h") {
4261
- dependencies.stdout("Usage: siteplane <connect|setup|analytics|booking>");
4288
+ dependencies.stdout("Usage: siteplane <init|setup|analytics|booking>");
4262
4289
  return { exitCode: 0 };
4263
4290
  }
4264
- dependencies.stdout("Usage: siteplane <connect|setup|analytics|booking>");
4291
+ dependencies.stdout("Usage: siteplane <init|setup|analytics|booking>");
4265
4292
  return { exitCode: 1 };
4266
4293
  }
4267
4294
  async function runAnalyticsCommand(args, dependencies) {
@@ -4301,7 +4328,9 @@ async function runAnalyticsCommand(args, dependencies) {
4301
4328
  });
4302
4329
  const siteKeyLookup = getAnalyticsKeyLookup(rawPublicKey);
4303
4330
  if (!siteKeyLookup) {
4304
- throw new Error("Project config contains an invalid Analytics public site key.");
4331
+ throw new Error(
4332
+ "Project config contains an invalid Analytics public site key."
4333
+ );
4305
4334
  }
4306
4335
  const agentClient = readAnalyticsAgentClient(subcommandArgs);
4307
4336
  const result = await dependencies.commands.analyticsInitCommand({
@@ -4318,9 +4347,12 @@ async function runAnalyticsCommand(args, dependencies) {
4318
4347
  return { exitCode: 0 };
4319
4348
  }
4320
4349
  if (subcommand === "check" || subcommand === "sync") {
4321
- const sourceFilePaths = await dependencies.commands.resolveScanFilePaths([], {
4322
- projectDir
4323
- });
4350
+ const sourceFilePaths = await dependencies.commands.resolveScanFilePaths(
4351
+ [],
4352
+ {
4353
+ projectDir
4354
+ }
4355
+ );
4324
4356
  const artifactFilePaths = [join7(projectDir, ".siteplane/analytics.md")];
4325
4357
  const cspFilePaths = await existingPaths([
4326
4358
  join7(projectDir, "next.config.js"),
@@ -4378,7 +4410,12 @@ async function runAnalyticsCommand(args, dependencies) {
4378
4410
  config,
4379
4411
  payload,
4380
4412
  apply: subcommandArgs.includes("--apply"),
4381
- ...readOption(subcommandArgs, "--confirm-hash") ? { confirmHash: readOption(subcommandArgs, "--confirm-hash") } : {},
4413
+ ...readOption(subcommandArgs, "--confirm-hash") ? {
4414
+ confirmHash: readOption(
4415
+ subcommandArgs,
4416
+ "--confirm-hash"
4417
+ )
4418
+ } : {},
4382
4419
  yes: subcommandArgs.includes("--yes")
4383
4420
  }),
4384
4421
  dependencies
@@ -4403,6 +4440,15 @@ async function runSetupCommand(args, dependencies) {
4403
4440
  dependencies.stdout(JSON.stringify(result, null, 2));
4404
4441
  return { exitCode: result.status === "action_required" ? 1 : 0 };
4405
4442
  }
4443
+ if (area === "activity") {
4444
+ const result = await dependencies.commands.siteSetupActivityCommand({
4445
+ projectDir,
4446
+ phase: readRequiredOption(areaArgs, "--phase"),
4447
+ ...connectionOptions
4448
+ });
4449
+ dependencies.stdout(JSON.stringify(result, null, 2));
4450
+ return { exitCode: result.status === "action_required" ? 1 : 0 };
4451
+ }
4406
4452
  if (area === "apply") {
4407
4453
  const editorDefinition = await dependencies.readJsonFile(
4408
4454
  readRequiredOption(areaArgs, "--definition")
@@ -4425,9 +4471,7 @@ async function runSetupCommand(args, dependencies) {
4425
4471
  dependencies.stdout(JSON.stringify(result, null, 2));
4426
4472
  return { exitCode: result.status === "ready_for_review" ? 0 : 1 };
4427
4473
  }
4428
- dependencies.stdout(
4429
- "Usage: siteplane setup <context|apply|verify>"
4430
- );
4474
+ dependencies.stdout("Usage: siteplane setup <context|activity|apply|verify>");
4431
4475
  return { exitCode: 1 };
4432
4476
  }
4433
4477
  async function runBookingCommand(args, dependencies) {
@@ -4461,9 +4505,12 @@ async function runBookingCommand(args, dependencies) {
4461
4505
  return { exitCode: 0 };
4462
4506
  }
4463
4507
  if (subcommand === "check") {
4464
- const sourceFilePaths = await dependencies.commands.resolveScanFilePaths(subcommandArgs, {
4465
- projectDir
4466
- });
4508
+ const sourceFilePaths = await dependencies.commands.resolveScanFilePaths(
4509
+ subcommandArgs,
4510
+ {
4511
+ projectDir
4512
+ }
4513
+ );
4467
4514
  const result = await dependencies.commands.bookingCheckCommand({
4468
4515
  manifestPath,
4469
4516
  sourceFilePaths
@@ -4516,9 +4563,7 @@ async function runBookingCommand(args, dependencies) {
4516
4563
  dependencies.stdout(await response.text());
4517
4564
  return { exitCode: response.ok ? 0 : 1 };
4518
4565
  }
4519
- dependencies.stdout(
4520
- "Usage: siteplane booking <init|check|sync|test>"
4521
- );
4566
+ dependencies.stdout("Usage: siteplane booking <init|check|sync|test>");
4522
4567
  return { exitCode: 1 };
4523
4568
  }
4524
4569
  async function readBookingProjectState(projectDir, manifestPath, dependencies) {
@@ -4547,7 +4592,9 @@ function createDefaultDependencies() {
4547
4592
  env: process.env,
4548
4593
  stdout: (line) => console.log(line),
4549
4594
  stderr: (line) => console.error(line),
4550
- readJsonFile: async (path) => JSON.parse(await readFile8(resolve(process.cwd(), path), "utf8")),
4595
+ readJsonFile: async (path) => JSON.parse(
4596
+ await readFile8(resolve(process.cwd(), path), "utf8")
4597
+ ),
4551
4598
  readPackageVersion: async () => {
4552
4599
  const packageJson = JSON.parse(
4553
4600
  await readFile8(new URL("../../package.json", import.meta.url), "utf8")
@@ -4557,8 +4604,8 @@ function createDefaultDependencies() {
4557
4604
  commands: {
4558
4605
  siteSetupApplyCommand,
4559
4606
  siteSetupContextCommand,
4607
+ siteSetupActivityCommand,
4560
4608
  siteSetupVerifyCommand,
4561
- connectCommand,
4562
4609
  initCommand,
4563
4610
  bookingInitCommand,
4564
4611
  bookingCheckCommand,