@artifactshare/cli 0.13.2 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -4,6 +4,7 @@ import { cli, define, lazy } from "gunshi";
4
4
  import { generate } from "gunshi/generator";
5
5
  import { chmodSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, statSync, watch, writeFileSync } from "node:fs";
6
6
  import { pathToFileURL } from "node:url";
7
+ import { z } from "zod";
7
8
  import { execFile, spawn } from "node:child_process";
8
9
  import { appendFile, chmod, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
9
10
  import { arch, homedir, platform } from "node:os";
@@ -14,9 +15,602 @@ import { Blob, Buffer as Buffer$1 } from "node:buffer";
14
15
  import { EventEmitter } from "node:events";
15
16
  import { createServer } from "node:http";
16
17
  import { promisify } from "node:util";
18
+ //#region ../contract/dist/index.js
19
+ const CLI_DEVICE_CLIENT_ID = "artifactshare-cli";
20
+ const stringId = z.string().min(1);
21
+ const timestamp = z.string().min(1);
22
+ const url = z.string().url();
23
+ const nullableTimestamp = timestamp.nullable();
24
+ const ArtifactKindSchema = z.enum([
25
+ "markdown_page",
26
+ "html_page",
27
+ "static_site",
28
+ "spa",
29
+ "workspace_app"
30
+ ]);
31
+ const UploadArtifactKindSchema = z.enum([
32
+ "markdown_page",
33
+ "html_page",
34
+ "static_site"
35
+ ]);
36
+ const VisibilitySchema = z.enum([
37
+ "private",
38
+ "workspace",
39
+ "project",
40
+ "link"
41
+ ]);
42
+ const ProjectBaseVisibilitySchema = z.enum(["workspace", "private"]);
43
+ const ApiErrorSchema = z.object({
44
+ code: stringId,
45
+ message: z.string().min(1),
46
+ details: z.record(z.string(), z.unknown()).optional(),
47
+ why: z.string().optional(),
48
+ hint: z.string().optional(),
49
+ recovery: z.object({
50
+ kind: stringId,
51
+ command: z.string().optional()
52
+ }).optional()
53
+ });
54
+ const ApiErrorResponseSchema = z.object({ error: ApiErrorSchema });
55
+ /** OAuth device endpoints use the RFC 8628 string error envelope. */
56
+ const OAuthErrorResponseSchema = z.object({
57
+ error: stringId,
58
+ error_description: z.string().optional()
59
+ });
60
+ z.object({
61
+ error: ApiErrorSchema,
62
+ agent_recoverable: z.boolean(),
63
+ requires_human: z.boolean()
64
+ });
65
+ z.object({ id: stringId });
66
+ z.object({
67
+ id: stringId,
68
+ "*": stringId
69
+ });
70
+ z.object({ id: stringId });
71
+ z.object({
72
+ refresh_token: z.string().min(1).max(256),
73
+ /** Optional for CLIs released before refresh-credential rotation. */
74
+ rotation_request_id: z.string().min(1).max(128).optional()
75
+ });
76
+ z.object({ refresh_token: z.string().min(1).max(256) });
77
+ const LegacyCliAuthRefreshResponseSchema = z.object({
78
+ access_token: stringId,
79
+ token_type: z.string().min(1),
80
+ expires_at: timestamp
81
+ });
82
+ const RotatingCliAuthRefreshResponseSchema = z.object({
83
+ access_token: stringId,
84
+ token_type: z.string().min(1),
85
+ expires_at: timestamp,
86
+ refresh_token: stringId,
87
+ refresh_token_expires_at: timestamp
88
+ });
89
+ /**
90
+ * New servers return rotating credentials. The legacy response remains a
91
+ * valid read shape so a client can talk to a server during a rolling update.
92
+ */
93
+ const CliAuthRefreshResponseSchema = z.union([RotatingCliAuthRefreshResponseSchema, LegacyCliAuthRefreshResponseSchema]);
94
+ z.object({
95
+ device_name: z.string().max(100).nullable().optional(),
96
+ device_id: z.string().max(100).nullable().optional()
97
+ });
98
+ const CliAuthRefreshCredentialsResponseSchema = z.object({
99
+ refresh_token: stringId,
100
+ refresh_token_expires_at: timestamp
101
+ });
102
+ z.object({ refresh_token: z.string().min(1).max(256) });
103
+ z.object({ revoked: z.literal(true) });
104
+ const DeviceAuthorizationPresetSchema = z.enum(["unrestricted", "agent"]);
105
+ z.object({
106
+ client_id: z.literal(CLI_DEVICE_CLIENT_ID),
107
+ preset: DeviceAuthorizationPresetSchema.optional(),
108
+ device_name: z.string().max(100).nullable().optional(),
109
+ project_selector: z.string().refine((value) => {
110
+ const size = Array.from(value.trim()).length;
111
+ return size >= 1 && size <= 120;
112
+ }, "project_selector must contain 1 to 120 Unicode code points after trimming").optional()
113
+ }).superRefine((value, context) => {
114
+ if (value.preset !== "agent" && value.project_selector !== void 0) context.addIssue({
115
+ code: "custom",
116
+ path: ["project_selector"],
117
+ message: "project_selector requires the agent preset"
118
+ });
119
+ });
120
+ const DeviceCodeResponseSchema = z.object({
121
+ device_code: stringId,
122
+ user_code: stringId,
123
+ verification_uri: url,
124
+ /** Older auth responses may omit this convenience URL or return null. */
125
+ verification_uri_complete: url.nullable().optional(),
126
+ expires_in: z.number().int().nonnegative(),
127
+ interval: z.number().int().nonnegative()
128
+ });
129
+ z.object({
130
+ grant_type: z.literal("urn:ietf:params:oauth:grant-type:device_code"),
131
+ device_code: stringId,
132
+ client_id: z.literal(CLI_DEVICE_CLIENT_ID)
133
+ });
134
+ const DeviceTokenResponseSchema = z.object({
135
+ access_token: stringId,
136
+ token_type: z.string().min(1).refine((value) => value.toLowerCase() === "bearer", { message: "token_type must be Bearer" }),
137
+ expires_in: z.number().int().nonnegative().optional()
138
+ });
139
+ z.object({
140
+ userCode: stringId,
141
+ project_id: stringId.optional()
142
+ });
143
+ z.object({ user_code: stringId });
144
+ z.object({ status: z.string().optional() });
145
+ z.object({ userCode: stringId });
146
+ z.object({ user_code: stringId });
147
+ const FixedAgentApprovalProjectSchema = z.object({
148
+ id: stringId,
149
+ name: z.string(),
150
+ baseVisibility: ProjectBaseVisibilitySchema,
151
+ updatedAt: timestamp
152
+ });
153
+ const AgentApprovalSchema = z.object({
154
+ preset: z.literal("agent"),
155
+ deviceName: z.string().nullable(),
156
+ projectSelector: z.string().nullable(),
157
+ fixedProject: FixedAgentApprovalProjectSchema.nullable(),
158
+ fixedProjectError: z.boolean()
159
+ });
160
+ z.object({ agentApproval: AgentApprovalSchema.nullable() });
161
+ const CliUserSchema = z.object({
162
+ id: stringId,
163
+ email: z.string()
164
+ });
165
+ const CliWorkspaceSchema = z.object({
166
+ id: stringId,
167
+ hosted_domain: z.string().nullable()
168
+ });
169
+ const CliWhoamiResponseSchema = z.object({
170
+ user: CliUserSchema,
171
+ workspace: CliWorkspaceSchema,
172
+ auth: z.object({ kind: z.literal("bearer_or_session") }).optional()
173
+ });
174
+ const DoctorAuthoritySchema = z.object({
175
+ preset: DeviceAuthorizationPresetSchema,
176
+ project_id: stringId.nullable()
177
+ });
178
+ const DoctorUploadSchema = z.union([z.object({ ok: z.literal(true) }), z.object({
179
+ ok: z.literal(false),
180
+ code: stringId,
181
+ message: z.string()
182
+ })]);
183
+ const CliDoctorResponseSchema = z.object({
184
+ user: CliUserSchema.extend({ id: stringId.optional() }),
185
+ workspace: CliWorkspaceSchema.optional(),
186
+ auth: z.object({
187
+ kind: z.literal("bearer_or_session").optional(),
188
+ ok: z.literal(true),
189
+ authority: DoctorAuthoritySchema.optional()
190
+ }),
191
+ upload: DoctorUploadSchema
192
+ });
193
+ z.object({
194
+ publish_key: z.string().optional(),
195
+ expected_version: z.string().optional(),
196
+ artifact_kind: z.literal("static_site").optional(),
197
+ container_id: z.string().optional()
198
+ });
199
+ const VersionLabelSchema = z.string().refine((value) => Array.from(value).length >= 1 && Array.from(value).length <= 80 && /[^\p{Default_Ignorable_Code_Point}\p{Zs}]/u.test(value) && !/[^\p{L}\p{M}\p{N}\p{P}\p{S}\p{Zs}\u200D]/u.test(value), "Label must contain 1–80 Unicode code points using letters, marks, numbers, punctuation, symbols, spaces, or joined emoji.");
200
+ const VersionLabelInputSchema = z.string().transform((value) => value.normalize("NFC").replace(/^\p{Zs}+|\p{Zs}+$/gu, "")).pipe(VersionLabelSchema);
201
+ z.object({
202
+ label: VersionLabelInputSchema.optional(),
203
+ expected_version: z.string().optional(),
204
+ artifact_kind: z.literal("static_site").optional()
205
+ });
206
+ /** Preserve the file and its bytes without depending on a global File class. */
207
+ const MultipartFilePartSchema = z.custom((value) => {
208
+ if (typeof value !== "object" || value === null) return false;
209
+ return "name" in value && typeof value.name === "string" && "size" in value && typeof value.size === "number" && Number.isInteger(value.size) && value.size >= 0 && "type" in value && typeof value.type === "string" && "arrayBuffer" in value && typeof value.arrayBuffer === "function";
210
+ }, "Expected a multipart file part");
211
+ z.object({ file: z.array(MultipartFilePartSchema).min(1) }).extend({
212
+ visibility: VisibilitySchema.optional(),
213
+ grant_email: z.array(z.string()).optional(),
214
+ container_id: z.string().optional(),
215
+ link_expires_at: z.string().optional(),
216
+ slack_notify: z.string().optional()
217
+ });
218
+ const UploadWarningSchema = z.object({
219
+ code: z.literal("slack_reauthorization_required"),
220
+ message: z.string()
221
+ });
222
+ const ArtifactUploadResponseSchema = z.object({
223
+ id: stringId,
224
+ versionId: stringId,
225
+ artifactKind: UploadArtifactKindSchema,
226
+ visibility: VisibilitySchema.optional(),
227
+ link_expires_at: nullableTimestamp.optional(),
228
+ containerId: stringId.nullable().optional(),
229
+ shareUrl: url,
230
+ /** Present only for publish-key requests. */
231
+ created: z.boolean().optional(),
232
+ warnings: z.array(UploadWarningSchema).optional()
233
+ });
234
+ const ArtifactVersionUpdateResponseSchema = z.object({
235
+ number: z.number().int().positive().optional(),
236
+ label: VersionLabelSchema.nullable().optional(),
237
+ id: stringId.optional(),
238
+ versionId: stringId,
239
+ shareUrl: url.optional(),
240
+ /** Static-site replacement responses include this field. */
241
+ artifactKind: UploadArtifactKindSchema.optional()
242
+ });
243
+ z.object({
244
+ id: stringId,
245
+ currentVersionId: stringId.nullable()
246
+ });
247
+ z.object({
248
+ /** Empty string selects the unfiled home list. */
249
+ project_id: z.string().optional(),
250
+ query: z.string().optional(),
251
+ cursor: z.string().optional()
252
+ });
253
+ const ArtifactIncludeSchema = z.enum(["versions", "comments"]);
254
+ z.object({
255
+ offset: z.number().int().nonnegative().optional(),
256
+ include: z.array(ArtifactIncludeSchema).optional()
257
+ });
258
+ z.object({
259
+ offset: z.string().regex(/^\d+$/).optional(),
260
+ include: z.array(z.string()).optional().superRefine((values, context) => {
261
+ if (!values) return;
262
+ for (const [index, value] of values.entries()) for (const item of value.split(",")) {
263
+ const candidate = item.trim();
264
+ if (!candidate) continue;
265
+ if (!ArtifactIncludeSchema.safeParse(candidate).success) context.addIssue({
266
+ code: "custom",
267
+ path: [index],
268
+ message: "include must be versions or comments"
269
+ });
270
+ }
271
+ })
272
+ });
273
+ const ArtifactVersionSchema = z.object({
274
+ label: VersionLabelSchema.optional(),
275
+ version_id: stringId,
276
+ status: z.string(),
277
+ size_bytes: z.number().nonnegative(),
278
+ created_at: timestamp,
279
+ published_at: nullableTimestamp,
280
+ is_current: z.boolean(),
281
+ creator: z.object({
282
+ kind: z.enum(["human", "agent"]),
283
+ name: z.string(),
284
+ email: z.string().nullable(),
285
+ agent_profile_id: stringId.nullable()
286
+ }).nullable()
287
+ });
288
+ const ArtifactReadResponseSchema = z.object({
289
+ id: stringId,
290
+ share_url: url,
291
+ version_id: stringId,
292
+ format: z.enum(["html", "markdown"]),
293
+ content: z.string(),
294
+ size_bytes: z.number().nonnegative(),
295
+ truncated: z.boolean(),
296
+ next_offset: z.number().int().nonnegative().nullable(),
297
+ link_expires_at: nullableTimestamp.optional(),
298
+ project_id: stringId.nullable().optional(),
299
+ versions: z.array(ArtifactVersionSchema).optional(),
300
+ versions_has_more: z.boolean().optional(),
301
+ comments: z.array(z.lazy(() => CommentThreadSchema)).optional(),
302
+ comments_has_more: z.boolean().optional()
303
+ });
304
+ const ArtifactDeleteResponseSchema = z.object({
305
+ id: stringId,
306
+ deleted: z.literal(true)
307
+ });
308
+ z.object({ content: z.string().min(1) });
309
+ const ArtifactAppendResponseSchema = z.object({
310
+ id: stringId.optional(),
311
+ versionId: stringId,
312
+ shareUrl: url.optional(),
313
+ artifactKind: UploadArtifactKindSchema.optional()
314
+ });
315
+ const DownloadManifestFileSchema = z.object({
316
+ path: z.string().min(1),
317
+ size_bytes: z.number().int().nonnegative(),
318
+ content_type: z.string().min(1),
319
+ sha256: z.string()
320
+ });
321
+ const DownloadManifestResponseSchema = z.object({
322
+ id: stringId,
323
+ share_url: url,
324
+ version_id: stringId,
325
+ artifact_kind: UploadArtifactKindSchema,
326
+ files: z.array(DownloadManifestFileSchema),
327
+ total_size_bytes: z.number().int().nonnegative(),
328
+ project_id: stringId.nullable().optional()
329
+ });
330
+ const ArtifactsListEntrySchema = z.object({
331
+ id: stringId,
332
+ title: z.string(),
333
+ share_url: url,
334
+ visibility: VisibilitySchema,
335
+ link_expires_at: nullableTimestamp.optional(),
336
+ updated_at: timestamp,
337
+ project_id: stringId.nullable(),
338
+ owner_email: z.string().optional(),
339
+ artifact_kind: ArtifactKindSchema.optional()
340
+ });
341
+ const ArtifactsListResponseSchema = z.object({
342
+ artifacts: z.array(ArtifactsListEntrySchema),
343
+ limit: z.number().int().nonnegative(),
344
+ has_more: z.boolean(),
345
+ next_cursor: z.string().nullable()
346
+ });
347
+ const CommentAnchorSchema = z.union([z.object({
348
+ kind: z.literal("artifact"),
349
+ quoted_text: z.null(),
350
+ state: z.null()
351
+ }), z.object({
352
+ kind: z.literal("text"),
353
+ quoted_text: z.string(),
354
+ state: z.enum(["attached", "orphaned"])
355
+ })]);
356
+ const CommentMessageSchema = z.object({
357
+ message_id: stringId,
358
+ author_name: z.string().nullable(),
359
+ author_email: z.string(),
360
+ agent: z.string().nullable(),
361
+ body: z.string(),
362
+ created_at: timestamp,
363
+ updated_at: timestamp
364
+ });
365
+ const CommentThreadSchema = z.object({
366
+ id: stringId,
367
+ status: z.enum(["open", "resolved"]),
368
+ resolved_at: nullableTimestamp,
369
+ created_at: timestamp,
370
+ updated_at: timestamp,
371
+ anchor: CommentAnchorSchema,
372
+ messages: z.array(CommentMessageSchema)
373
+ });
374
+ const CommentPostRequestSchema = z.object({
375
+ action: z.never().optional(),
376
+ body: z.string().min(1).max(4e3),
377
+ reply_to: z.string().min(1).max(128).optional(),
378
+ quote: z.string().min(1).max(1e3).optional(),
379
+ quote_before: z.string().min(1).max(200).optional(),
380
+ quote_after: z.string().min(1).max(200).optional(),
381
+ agent: z.string().refine((value) => value.trim().length <= 30, "agent must contain at most 30 characters after trimming").optional()
382
+ }).superRefine((value, context) => {
383
+ if (value.reply_to !== void 0 && value.quote !== void 0) context.addIssue({
384
+ code: "custom",
385
+ path: ["quote"],
386
+ message: "A quote can only anchor a new thread, not a reply."
387
+ });
388
+ if (value.quote === void 0 && (value.quote_before !== void 0 || value.quote_after !== void 0)) context.addIssue({
389
+ code: "custom",
390
+ path: ["quote"],
391
+ message: "quote_before and quote_after require quote"
392
+ });
393
+ });
394
+ const CommentEditRequestSchema = z.object({
395
+ action: z.literal("edit"),
396
+ message_id: stringId.max(128),
397
+ body: z.string().min(1).max(4e3)
398
+ });
399
+ const CommentResolveRequestSchema = z.object({
400
+ action: z.literal("resolve"),
401
+ thread_id: stringId.max(128)
402
+ });
403
+ const CommentReopenRequestSchema = z.object({
404
+ action: z.literal("reopen"),
405
+ thread_id: stringId.max(128)
406
+ });
407
+ const CommentDeleteRequestSchema = z.object({
408
+ action: z.literal("delete"),
409
+ thread_id: stringId.max(128),
410
+ message_id: stringId.max(128).optional()
411
+ });
412
+ const CommentActionRequestSchema = z.union([
413
+ CommentEditRequestSchema,
414
+ CommentResolveRequestSchema,
415
+ CommentReopenRequestSchema,
416
+ CommentDeleteRequestSchema
417
+ ]);
418
+ z.union([CommentActionRequestSchema, CommentPostRequestSchema]);
419
+ const CommentsListResponseSchema = z.object({
420
+ artifact_id: stringId,
421
+ share_url: url.nullable().optional(),
422
+ comments: z.array(CommentThreadSchema),
423
+ has_more: z.boolean().optional()
424
+ });
425
+ const CommentPostResponseSchema = z.object({
426
+ artifact_id: stringId,
427
+ share_url: url.nullable().optional(),
428
+ thread_id: stringId,
429
+ reply: z.boolean(),
430
+ thread: CommentThreadSchema
431
+ });
432
+ const CommentActionResponseSchema = z.object({
433
+ artifact_id: stringId,
434
+ share_url: url.nullable().optional(),
435
+ thread_id: stringId,
436
+ thread: CommentThreadSchema
437
+ });
438
+ const CommentDeleteResponseSchema = z.object({
439
+ artifact_id: stringId,
440
+ share_url: url.nullable().optional(),
441
+ thread_id: stringId,
442
+ deleted: z.literal(true),
443
+ thread_deleted: z.boolean(),
444
+ thread: CommentThreadSchema.optional()
445
+ });
446
+ const ProjectListEntrySchema = z.object({
447
+ id: stringId,
448
+ name: z.string(),
449
+ description: z.string().nullable(),
450
+ base_visibility: z.string().min(1),
451
+ file_count: z.number().int().nonnegative().nullable(),
452
+ updated_at: timestamp.nullable()
453
+ });
454
+ const ProjectsListResponseSchema = z.object({ projects: z.array(ProjectListEntrySchema) });
455
+ z.object({
456
+ name: z.string().min(1),
457
+ description: z.string().nullable().optional(),
458
+ base_visibility: ProjectBaseVisibilitySchema.nullable().optional()
459
+ });
460
+ const ProjectCreateResponseSchema = z.object({ project: z.object({
461
+ id: stringId,
462
+ name: z.string(),
463
+ description: z.string().nullable(),
464
+ base_visibility: ProjectBaseVisibilitySchema
465
+ }) });
466
+ z.object({
467
+ name: z.string().optional(),
468
+ description: z.string().nullable().optional(),
469
+ base_visibility: ProjectBaseVisibilitySchema.nullable().optional(),
470
+ add_emails: z.array(z.string()).optional(),
471
+ remove_emails: z.array(z.string()).optional(),
472
+ archived: z.boolean().optional()
473
+ }).refine((value) => Object.keys(value).length > 0, { message: "At least one project edit field is required" });
474
+ const ProjectEditResponseSchema = z.object({
475
+ project: z.object({
476
+ id: stringId,
477
+ name: z.string(),
478
+ description: z.string().nullable(),
479
+ base_visibility: ProjectBaseVisibilitySchema,
480
+ file_count: z.number().int().nonnegative().nullable(),
481
+ archived: z.boolean()
482
+ }),
483
+ audience: z.array(z.string())
484
+ });
485
+ const CliEditableVisibilitySchema = z.enum([
486
+ "private",
487
+ "workspace",
488
+ "link"
489
+ ]);
490
+ const CliDestinationSchema = z.union([z.literal("home"), z.object({ project_id: stringId })]);
491
+ const CliEditDestinationSchema = z.union([z.literal("home"), z.object({ project_id: z.string().trim().min(1) })]);
492
+ z.object({
493
+ title: z.string().optional(),
494
+ visibility: CliEditableVisibilitySchema.optional(),
495
+ link_expires_at: z.string().nullable().optional(),
496
+ add_emails: z.array(z.string()).optional(),
497
+ remove_emails: z.array(z.string()).optional(),
498
+ destination: CliEditDestinationSchema.optional()
499
+ }).refine((value) => Object.keys(value).length > 0, { message: "At least one edit field is required" });
500
+ const CliArtifactReferenceSchema = z.object({
501
+ id: stringId,
502
+ url: url.nullable().optional()
503
+ });
504
+ const CliArtifactDestinationSchema = z.union([z.object({
505
+ type: z.literal("home"),
506
+ project_id: z.null()
507
+ }), z.object({
508
+ type: z.literal("project"),
509
+ project_id: stringId
510
+ })]);
511
+ const CliEditResponseSchema = z.object({
512
+ artifact: CliArtifactReferenceSchema,
513
+ title: z.string(),
514
+ destination: CliArtifactDestinationSchema,
515
+ share: z.object({
516
+ visibility: VisibilitySchema,
517
+ link_expires_at: nullableTimestamp.optional()
518
+ })
519
+ });
520
+ z.object({ destination: CliDestinationSchema });
521
+ const CliMoveResponseSchema = z.object({
522
+ artifact: CliArtifactReferenceSchema,
523
+ destination: CliArtifactDestinationSchema,
524
+ share: z.object({
525
+ visibility: VisibilitySchema,
526
+ project_audience_may_change: z.boolean()
527
+ })
528
+ });
529
+ z.object({ q: z.string().trim().min(1) });
530
+ const ResolveMatchSchema = z.object({
531
+ kind: z.enum([
532
+ "url",
533
+ "id",
534
+ "title",
535
+ "project_name"
536
+ ]),
537
+ confidence: z.enum(["exact", "candidate"])
538
+ });
539
+ const ArtifactResolveCandidateSchema = z.object({
540
+ kind: z.literal("artifact"),
541
+ id: stringId,
542
+ title: z.string(),
543
+ artifact_kind: ArtifactKindSchema,
544
+ visibility: VisibilitySchema,
545
+ project: z.object({
546
+ id: stringId,
547
+ name: z.string()
548
+ }).nullable(),
549
+ owner: z.object({
550
+ id: stringId,
551
+ email: z.string()
552
+ }),
553
+ updated_at: timestamp,
554
+ match: ResolveMatchSchema
555
+ });
556
+ const VersionResolveCandidateSchema = z.object({
557
+ kind: z.literal("version"),
558
+ id: stringId,
559
+ artifact_id: stringId,
560
+ version_id: stringId,
561
+ ordinal: z.number().int().nonnegative(),
562
+ is_current: z.boolean(),
563
+ published_at: nullableTimestamp,
564
+ size_bytes: z.number().nonnegative(),
565
+ match: ResolveMatchSchema
566
+ });
567
+ const ProjectResolveCandidateSchema = z.object({
568
+ kind: z.literal("project"),
569
+ id: stringId,
570
+ name: z.string(),
571
+ description: z.string().nullable(),
572
+ base_visibility: z.string().min(1),
573
+ file_count: z.number().int().nonnegative(),
574
+ updated_at: timestamp,
575
+ match: ResolveMatchSchema
576
+ });
577
+ const ResolveCandidateSchema = z.union([
578
+ ArtifactResolveCandidateSchema,
579
+ VersionResolveCandidateSchema,
580
+ ProjectResolveCandidateSchema
581
+ ]);
582
+ const ResolveResponseSchema = z.object({
583
+ query: z.string(),
584
+ candidates: z.array(ResolveCandidateSchema),
585
+ has_more: z.boolean()
586
+ });
587
+ const CLI_AUTH_REFRESH_RESPONSE_SCHEMA = CliAuthRefreshResponseSchema;
588
+ const CLI_AUTH_REFRESH_CREDENTIALS_RESPONSE_SCHEMA = CliAuthRefreshCredentialsResponseSchema;
589
+ const DEVICE_CODE_RESPONSE_SCHEMA = DeviceCodeResponseSchema;
590
+ const DEVICE_TOKEN_RESPONSE_SCHEMA = DeviceTokenResponseSchema;
591
+ const CLI_WHOAMI_RESPONSE_SCHEMA = CliWhoamiResponseSchema;
592
+ const CLI_DOCTOR_RESPONSE_SCHEMA = CliDoctorResponseSchema;
593
+ const ARTIFACT_UPLOAD_RESPONSE_SCHEMA = ArtifactUploadResponseSchema;
594
+ const ARTIFACT_VERSION_UPDATE_RESPONSE_SCHEMA = ArtifactVersionUpdateResponseSchema;
595
+ const ARTIFACT_READ_RESPONSE_SCHEMA = ArtifactReadResponseSchema;
596
+ const ARTIFACT_DELETE_RESPONSE_SCHEMA = ArtifactDeleteResponseSchema;
597
+ const ARTIFACT_APPEND_RESPONSE_SCHEMA = ArtifactAppendResponseSchema;
598
+ const ARTIFACTS_LIST_RESPONSE_SCHEMA = ArtifactsListResponseSchema;
599
+ const DOWNLOAD_MANIFEST_RESPONSE_SCHEMA = DownloadManifestResponseSchema;
600
+ const COMMENTS_LIST_RESPONSE_SCHEMA = CommentsListResponseSchema;
601
+ const COMMENT_POST_RESPONSE_SCHEMA = CommentPostResponseSchema;
602
+ const COMMENT_ACTION_RESPONSE_SCHEMA = CommentActionResponseSchema;
603
+ const COMMENT_DELETE_RESPONSE_SCHEMA = CommentDeleteResponseSchema;
604
+ const PROJECTS_LIST_RESPONSE_SCHEMA = ProjectsListResponseSchema;
605
+ const PROJECT_CREATE_RESPONSE_SCHEMA = ProjectCreateResponseSchema;
606
+ const PROJECT_EDIT_RESPONSE_SCHEMA = ProjectEditResponseSchema;
607
+ const CLI_EDIT_RESPONSE_SCHEMA = CliEditResponseSchema;
608
+ const CLI_MOVE_RESPONSE_SCHEMA = CliMoveResponseSchema;
609
+ const RESOLVE_RESPONSE_SCHEMA = ResolveResponseSchema;
610
+ //#endregion
17
611
  //#region src/constants.ts
18
612
  const DEFAULT_BASE_URL = "https://artifactshare.com";
19
- const DEVICE_CLIENT_ID = "artifactshare-cli";
613
+ const DEVICE_CLIENT_ID = CLI_DEVICE_CLIENT_ID;
20
614
  const CLI_INVOCATION = "npm exec --yes --package=@artifactshare/cli -- artifactshare";
21
615
  const AGENT_DOWNLOAD_OUTPUT = "./artifact";
22
616
  const TOKEN_ENV_VAR = "ARTIFACTSHARE_TOKEN";
@@ -56,6 +650,7 @@ const VALUE_FLAGS = /* @__PURE__ */ new Set([
56
650
  "grant-email",
57
651
  "include",
58
652
  "key",
653
+ "label",
59
654
  "link-expires-at",
60
655
  "message-id",
61
656
  "name",
@@ -113,7 +708,11 @@ const COMMAND_NAMES = /* @__PURE__ */ new Set([
113
708
  "preview stop"
114
709
  ]);
115
710
  const SUBCOMMANDS = {
116
- artifacts: ["list", "get"],
711
+ artifacts: [
712
+ "list",
713
+ "get",
714
+ "delete"
715
+ ],
117
716
  comments: [
118
717
  "list",
119
718
  "post",
@@ -156,6 +755,8 @@ const SUBCOMMANDS = {
156
755
  const UPDATE_OPTION_KEYS = /* @__PURE__ */ new Set([
157
756
  "allowPlaintextTokenStore",
158
757
  "baseUrl",
758
+ "expectedVersion",
759
+ "label",
159
760
  "help",
160
761
  "insecureLocalhost",
161
762
  "json",
@@ -175,6 +776,10 @@ function isProfileCredentialSource(source) {
175
776
  function isRecord$1(value) {
176
777
  return typeof value === "object" && value !== null && !Array.isArray(value);
177
778
  }
779
+ /** Validate a wire value with the shared public contract without rewriting it. */
780
+ function isContract(schema, value) {
781
+ return schema.safeParse(value).success;
782
+ }
178
783
  function nonEmpty(value) {
179
784
  if (typeof value !== "string") return void 0;
180
785
  const trimmed = value.trim();
@@ -184,14 +789,16 @@ function nonEmpty(value) {
184
789
  //#region src/errors.ts
185
790
  const PROJECTS_LIST_COMMAND = `${CLI_INVOCATION} projects list --json`;
186
791
  function apiError(body) {
187
- const error = body?.error;
792
+ const contracted = isContract(ApiErrorResponseSchema, body) ? body.error : void 0;
793
+ const record = isRecord$1(body) ? body : void 0;
794
+ const error = contracted ?? record?.error;
188
795
  if (typeof error === "string") return {
189
796
  code: error,
190
797
  message: void 0
191
798
  };
192
799
  return {
193
- code: normalizeApiCode(error?.code),
194
- message: error?.message
800
+ code: normalizeApiCode(isRecord$1(error) ? error.code : void 0),
801
+ message: isRecord$1(error) && typeof error.message === "string" ? error.message : void 0
195
802
  };
196
803
  }
197
804
  function mapApiError(status, body, options = {}) {
@@ -206,16 +813,6 @@ function mapApiError(status, body, options = {}) {
206
813
  }
207
814
  return tokenInvalidError();
208
815
  }
209
- if (apiCode === "upload-not-allowed") return cliError({
210
- code: "upload_not_allowed",
211
- message: "Sharing is temporarily unavailable.",
212
- why: "Artifact Share has paused sharing for now.",
213
- hint: "Contact Artifact Share support if you need sharing enabled.",
214
- agentRecoverable: false,
215
- requiresHuman: true,
216
- recovery: { kind: "ask_human" },
217
- details: { limit: "upload_access" }
218
- });
219
816
  if (apiCode === "self-upload-disabled") return cliError({
220
817
  code: "self_upload_disabled",
221
818
  message: "This account cannot upload its own files.",
@@ -245,7 +842,8 @@ function mapApiError(status, body, options = {}) {
245
842
  recovery: { kind: "ask_human" }
246
843
  });
247
844
  if (apiCode === "quota-exceeded") {
248
- const apiDetails = typeof body?.error === "object" && isRecord$1(body.error.details) ? body.error.details : void 0;
845
+ const rawError = isRecord$1(body) ? body.error : void 0;
846
+ const apiDetails = isRecord$1(rawError) && isRecord$1(rawError.details) ? rawError.details : void 0;
249
847
  const upgradeRequest = isRecord$1(apiDetails?.upgrade_request) ? apiDetails.upgrade_request : void 0;
250
848
  return cliError({
251
849
  code: "storage_limit_exceeded",
@@ -382,22 +980,28 @@ function mapApiError(status, body, options = {}) {
382
980
  recovery: { kind: "change_input" }
383
981
  });
384
982
  }
385
- if (options.artifactTarget && options.operation === "append" && apiCode === "version_conflict") {
386
- const current = typeof body?.error === "object" ? body.error.details : void 0;
983
+ if (options.artifactTarget && [
984
+ "append",
985
+ "update",
986
+ "share"
987
+ ].includes(options.operation ?? "") && apiCode === "version_conflict") {
988
+ const rawError = isRecord$1(body) ? body.error : void 0;
989
+ const current = isRecord$1(rawError) ? rawError.details : void 0;
387
990
  const currentVersionId = isRecord$1(current) && typeof current.current_version_id === "string" ? current.current_version_id : null;
388
991
  return cliError({
389
992
  code: "version_conflict",
390
- message: apiMessage ?? "The artifact changed before append.",
993
+ message: apiMessage ?? "The artifact changed before the update.",
391
994
  why: currentVersionId ? `The current version is ${currentVersionId}.` : "Another update was committed first.",
392
- hint: "Run the same append command again to append to the latest content.",
995
+ hint: options.operation === "append" ? "Run the same append command again to append to the latest content." : "Read the current version, reapply your changes, and retry with its version id.",
393
996
  agentRecoverable: true,
394
997
  requiresHuman: false,
395
- recovery: { kind: "retry_later" },
998
+ recovery: { kind: options.operation === "append" ? "retry_later" : "change_input" },
396
999
  ...currentVersionId ? { details: { current_version_id: currentVersionId } } : {}
397
1000
  });
398
1001
  }
399
1002
  if (apiCode === "project-limit-reached") {
400
- const apiDetails = typeof body?.error === "object" && isRecord$1(body.error.details) ? body.error.details : void 0;
1003
+ const rawError = isRecord$1(body) ? body.error : void 0;
1004
+ const apiDetails = isRecord$1(rawError) && isRecord$1(rawError.details) ? rawError.details : void 0;
401
1005
  const upgradeRequest = isRecord$1(apiDetails?.upgrade_request) ? apiDetails.upgrade_request : void 0;
402
1006
  return cliError({
403
1007
  code: "project_limit_reached",
@@ -410,6 +1014,24 @@ function mapApiError(status, body, options = {}) {
410
1014
  ...upgradeRequest ? { details: { upgrade_request: upgradeRequest } } : {}
411
1015
  });
412
1016
  }
1017
+ if (apiCode === "link-publish-rate-limited") return cliError({
1018
+ code: "link_publish_rate_limited",
1019
+ message: apiMessage ?? "This new workspace has reached its daily link share limit.",
1020
+ why: "New Free workspaces may publish a bounded number of links per day; the limit protects link sharing from abuse.",
1021
+ hint: "Share with specific people now and retry the link visibility after the window passes (about a day), or ask the owner about the workspace plan.",
1022
+ agentRecoverable: true,
1023
+ requiresHuman: false,
1024
+ recovery: { kind: "retry_later" }
1025
+ });
1026
+ if (apiCode === "link-sharing-plan-required" || apiCode === "link-sharing-disabled" || apiCode === "link-expiry-invalid") return cliError({
1027
+ code: apiCode.replaceAll("-", "_"),
1028
+ message: apiMessage ?? "The link sharing option is invalid.",
1029
+ why: apiCode === "link-sharing-plan-required" ? "Link sharing is unavailable for this workspace." : apiCode === "link-sharing-disabled" ? "Link sharing is paused for this workspace; the owner or a Team admin can resume it." : "The requested link expiry does not match the link sharing policy.",
1030
+ hint: apiCode === "link-expiry-invalid" ? "Pass a future RFC3339 UTC timestamp within the workspace maximum, or use --no-link-expiry when unlimited expiry is allowed." : "Ask a workspace owner or administrator to review the workspace plan or link sharing policy.",
1031
+ agentRecoverable: apiCode === "link-expiry-invalid",
1032
+ requiresHuman: apiCode !== "link-expiry-invalid",
1033
+ recovery: apiCode === "link-expiry-invalid" ? { kind: "change_input" } : { kind: "ask_human" }
1034
+ });
413
1035
  if (apiCode === "forbidden" || status === 403) return cliError({
414
1036
  code: "forbidden",
415
1037
  message: apiMessage ?? "You do not have permission to do that.",
@@ -467,15 +1089,6 @@ function mapApiError(status, body, options = {}) {
467
1089
  requiresHuman: false,
468
1090
  recovery: { kind: "change_input" }
469
1091
  });
470
- if (apiCode === "link-sharing-plan-required" || apiCode === "link-sharing-disabled" || apiCode === "link-expiry-invalid") return cliError({
471
- code: apiCode.replaceAll("-", "_"),
472
- message: apiMessage ?? "The link sharing option is invalid.",
473
- why: apiCode === "link-sharing-plan-required" ? "Link sharing is available only on Plus and Team plans." : apiCode === "link-sharing-disabled" ? "The Team workspace has disabled link sharing." : "The requested link expiry does not match the link sharing policy.",
474
- hint: apiCode === "link-expiry-invalid" ? "Pass a future RFC3339 UTC timestamp within the workspace maximum, or use --no-link-expiry when unlimited expiry is allowed." : "Ask a workspace owner or administrator to review the workspace plan or link sharing policy.",
475
- agentRecoverable: apiCode === "link-expiry-invalid",
476
- requiresHuman: apiCode !== "link-expiry-invalid",
477
- recovery: apiCode === "link-expiry-invalid" ? { kind: "change_input" } : { kind: "ask_human" }
478
- });
479
1092
  if ((options.editSettings || options.projectTarget) && apiCode === "too-many-grants") return cliError({
480
1093
  code: "too_many_grants",
481
1094
  message: apiMessage ?? "Too many people are shared.",
@@ -525,6 +1138,15 @@ function mapApiError(status, body, options = {}) {
525
1138
  requiresHuman: false,
526
1139
  recovery: { kind: "change_input" }
527
1140
  });
1141
+ if (options.artifactTarget && (options.operation === "update" || options.operation === "share") && status === 400 && apiCode === "expected-version-required") return cliError({
1142
+ code: "expected_version_required",
1143
+ message: apiMessage ?? "Agent updates require the current version id.",
1144
+ why: "Agent-preset updates require an expected version.",
1145
+ hint: "Retry update or share --key with --expected-version <version-id>, using data.version.id from the previous successful share or update output. If that output is unavailable, for single-file HTML and Markdown artifacts, artifacts get <target> --json returns the current version as data.version_id. For static sites, download <target> --json returns it as data.version.id. Check the returned current content (data.content, or the downloaded files for static sites) and reapply your changes to it if it differs from what you edited. Pass the returned value as --expected-version.",
1146
+ agentRecoverable: true,
1147
+ requiresHuman: false,
1148
+ recovery: { kind: "change_input" }
1149
+ });
528
1150
  if (status === 400) return cliError({
529
1151
  code: "validation_failed",
530
1152
  message: apiMessage ?? "The request input is invalid.",
@@ -534,15 +1156,6 @@ function mapApiError(status, body, options = {}) {
534
1156
  requiresHuman: false,
535
1157
  recovery: { kind: "change_input" }
536
1158
  });
537
- if (apiCode === "upload-policy-unavailable") return cliError({
538
- code: "service_unavailable",
539
- message: apiMessage ?? "Upload permission could not be checked.",
540
- why: "Artifact Share could not verify upload permission right now.",
541
- hint: "Retry later with the same command.",
542
- agentRecoverable: true,
543
- requiresHuman: false,
544
- recovery: { kind: "retry_later" }
545
- });
546
1159
  if (apiCode === "maintenance") return cliError({
547
1160
  code: "maintenance",
548
1161
  message: apiMessage ?? "Artifact Share is currently under maintenance.",
@@ -813,8 +1426,6 @@ function normalizeApiCode(value) {
813
1426
  }
814
1427
  function uploadBlockedHint(code) {
815
1428
  if (code === "self-upload-disabled") return "Sign in with Google or Microsoft on the Artifact Share website, then retry share.";
816
- if (code === "upload-not-allowed") return "Contact Artifact Share support; sharing is temporarily unavailable.";
817
- if (code === "upload-policy-unavailable") return "Retry doctor later; upload permission could not be checked.";
818
1429
  return "Resolve the upload issue, then retry share.";
819
1430
  }
820
1431
  function projectNotFoundByNameError() {
@@ -939,7 +1550,9 @@ function resolveArtifactId(input) {
939
1550
  } catch {
940
1551
  return null;
941
1552
  }
942
- const sandboxMatch = url.hostname.match(/^([A-Za-z0-9]+)\.sandbox\./);
1553
+ const linkHostMatch = url.hostname.match(/^([A-Za-z0-9]{10})(?:--v-[a-f0-9]+)?\.artifactshare\.link$/);
1554
+ if (linkHostMatch?.[1]) return linkHostMatch[1];
1555
+ const sandboxMatch = url.hostname.match(/^([A-Za-z0-9]+)(?:--v-[a-f0-9]+)?\.sandbox\./);
943
1556
  if (sandboxMatch?.[1]) return sandboxMatch[1];
944
1557
  const shareMatch = url.pathname.match(/^\/a\/([A-Za-z0-9]+)(?:\.data)?\/?$/);
945
1558
  if (shareMatch?.[1]) return shareMatch[1];
@@ -966,7 +1579,7 @@ function targetResolutionError(input, command) {
966
1579
  code: "target_not_found",
967
1580
  message: "Artifact target could not be resolved.",
968
1581
  why: `${TARGET_COMMAND_LABELS[command]} only accepts an artifact ID, share URL, or sandbox URL.`,
969
- hint: "Retry with an artifact ID, /a/<id> share URL, or sandbox URL. If you only have a title, resolve it to an ID first.",
1582
+ hint: "Retry with an artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL. If you only have a title, resolve it to an ID first.",
970
1583
  agentRecoverable: true,
971
1584
  requiresHuman: false,
972
1585
  recovery: { kind: "change_input" },
@@ -1074,7 +1687,10 @@ function commandNameFromArgv(argv) {
1074
1687
  const command = found?.command;
1075
1688
  if (found && command !== void 0 && SUBCOMMANDS[command]) {
1076
1689
  const sub = nextPositional(argv, found.index);
1077
- if (sub !== void 0 && SUBCOMMANDS[command].includes(sub)) return `${command} ${sub}`;
1690
+ if (sub !== void 0 && SUBCOMMANDS[command].includes(sub)) {
1691
+ if (command === "artifacts" && sub === "delete") return "delete";
1692
+ return `${command} ${sub}`;
1693
+ }
1078
1694
  }
1079
1695
  return command !== void 0 && COMMAND_NAMES.has(command) ? command : void 0;
1080
1696
  }
@@ -1354,31 +1970,26 @@ function updateSuccessFields(data) {
1354
1970
  };
1355
1971
  }
1356
1972
  function resolveSuccessFields(data) {
1357
- if (!isRecord$1(data)) return false;
1358
- return typeof data.query === "string" && Array.isArray(data.candidates) && typeof data.has_more === "boolean";
1973
+ return isContract(RESOLVE_RESPONSE_SCHEMA, data);
1359
1974
  }
1360
1975
  function artifactGetSuccessFields(data) {
1976
+ if (isContract(ARTIFACT_READ_RESPONSE_SCHEMA, data)) return true;
1361
1977
  if (!isRecord$1(data)) return false;
1362
1978
  return typeof data.id === "string" && typeof data.share_url === "string" && typeof data.version_id === "string" && (data.format === "html" || data.format === "markdown") && typeof data.content === "string" && typeof data.size_bytes === "number" && typeof data.truncated === "boolean" && (typeof data.next_offset === "number" || data.next_offset === null) && (data.link_expires_at === void 0 || typeof data.link_expires_at === "string" || data.link_expires_at === null);
1363
1979
  }
1364
1980
  function artifactsListSuccessFields(data) {
1365
- if (!isRecord$1(data)) return false;
1366
- return Array.isArray(data.artifacts) && data.artifacts.every((item) => {
1367
- if (!isRecord$1(item)) return false;
1368
- return typeof item.id === "string" && typeof item.title === "string" && typeof item.share_url === "string" && typeof item.visibility === "string" && (item.link_expires_at === void 0 || typeof item.link_expires_at === "string" || item.link_expires_at === null) && typeof item.updated_at === "string" && (typeof item.project_id === "string" || item.project_id === null) && (item.owner_email === void 0 || typeof item.owner_email === "string") && (item.artifact_kind === void 0 || typeof item.artifact_kind === "string");
1369
- }) && typeof data.limit === "number" && typeof data.has_more === "boolean" && (typeof data.next_cursor === "string" || data.next_cursor === null);
1981
+ return isContract(ARTIFACTS_LIST_RESPONSE_SCHEMA, data);
1370
1982
  }
1371
1983
  function deleteSuccessFields(data) {
1372
- if (!isRecord$1(data)) return false;
1373
- return typeof data.id === "string" && data.deleted === true;
1984
+ return isContract(ARTIFACT_DELETE_RESPONSE_SCHEMA, data);
1374
1985
  }
1375
1986
  function downloadManifestFields(data) {
1987
+ if (isContract(DOWNLOAD_MANIFEST_RESPONSE_SCHEMA, data)) return true;
1376
1988
  if (!isRecord$1(data)) return false;
1377
- return typeof data.id === "string" && typeof data.share_url === "string" && typeof data.version_id === "string" && typeof data.artifact_kind === "string" && Array.isArray(data.files) && data.files.every(downloadManifestFileFields) && typeof data.total_size_bytes === "number" && (data.project_id === void 0 || typeof data.project_id === "string" || data.project_id === null);
1378
- }
1379
- function downloadManifestFileFields(data) {
1380
- if (!isRecord$1(data)) return false;
1381
- return typeof data.path === "string" && typeof data.size_bytes === "number" && typeof data.content_type === "string" && typeof data.sha256 === "string";
1989
+ return typeof data.id === "string" && typeof data.share_url === "string" && typeof data.version_id === "string" && typeof data.artifact_kind === "string" && Array.isArray(data.files) && data.files.every((file) => {
1990
+ if (!isRecord$1(file)) return false;
1991
+ return typeof file.path === "string" && typeof file.size_bytes === "number" && typeof file.content_type === "string" && typeof file.sha256 === "string";
1992
+ }) && typeof data.total_size_bytes === "number" && (data.project_id === void 0 || typeof data.project_id === "string" || data.project_id === null);
1382
1993
  }
1383
1994
  //#endregion
1384
1995
  //#region src/api.ts
@@ -2973,9 +3584,10 @@ async function issueCliRefreshCredential(token, deviceName, deviceId, options, i
2973
3584
  baseUrl: baseUrlOf(options)
2974
3585
  });
2975
3586
  if (result.error) return { error: result.error };
2976
- if (typeof result.body?.refresh_token === "string" && typeof result.body.refresh_token_expires_at === "string") return {
2977
- refresh_token: result.body.refresh_token,
2978
- refresh_token_expires_at: result.body.refresh_token_expires_at
3587
+ const refresh = CLI_AUTH_REFRESH_CREDENTIALS_RESPONSE_SCHEMA.safeParse(result.body);
3588
+ if (refresh.success) return {
3589
+ refresh_token: refresh.data.refresh_token,
3590
+ refresh_token_expires_at: refresh.data.refresh_token_expires_at
2979
3591
  };
2980
3592
  return { error: validationError("Refresh credential response was invalid.", "Retry login. If this repeats, report the response shape.", "service_error") };
2981
3593
  }
@@ -3018,18 +3630,24 @@ function loginProjectSelector(value) {
3018
3630
  return { value: selector };
3019
3631
  }
3020
3632
  function isDeviceCodeResponse(body) {
3021
- if (!isRecord$1(body)) return false;
3022
- return typeof body.device_code === "string" && typeof body.user_code === "string" && typeof body.verification_uri === "string" && (typeof body.verification_uri_complete === "string" || body.verification_uri_complete === void 0) && typeof body.expires_in === "number" && typeof body.interval === "number";
3633
+ return DEVICE_CODE_RESPONSE_SCHEMA.safeParse(body).success;
3023
3634
  }
3024
3635
  function isDeviceTokenResponse(body) {
3025
- if (!isRecord$1(body)) return false;
3026
- return typeof body.access_token === "string" && typeof body.token_type === "string" && body.token_type.toLowerCase() === "bearer" && (typeof body.expires_in === "number" || body.expires_in === void 0);
3636
+ return DEVICE_TOKEN_RESPONSE_SCHEMA.safeParse(body).success;
3027
3637
  }
3028
3638
  function deviceTokenError(body) {
3639
+ const contracted = OAuthErrorResponseSchema.safeParse(body);
3640
+ if (contracted.success) return contracted.data.error;
3029
3641
  if (!isRecord$1(body)) return null;
3030
3642
  return typeof body.error === "string" ? body.error : null;
3031
3643
  }
3032
3644
  function whoamiProfile(body) {
3645
+ const contracted = CliWhoamiResponseSchema.safeParse(body);
3646
+ if (contracted.success) return {
3647
+ email: contracted.data.user.email,
3648
+ workspace_id: contracted.data.workspace.id,
3649
+ hosted_domain: contracted.data.workspace.hosted_domain
3650
+ };
3033
3651
  const record = isRecord$1(body) ? body : null;
3034
3652
  const user = record && isRecord$1(record.user) ? record.user : null;
3035
3653
  const workspace = record && isRecord$1(record.workspace) ? record.workspace : null;
@@ -3160,25 +3778,28 @@ async function refreshStoredProfileSession(profile, refreshToken, options) {
3160
3778
  error: mapApiError(response.status, body, { baseUrl: baseUrlOf(options) })
3161
3779
  };
3162
3780
  }
3163
- if (typeof body?.access_token !== "string" || body.access_token.length === 0 || body.token_type?.toLowerCase() !== "bearer" || typeof body.expires_at !== "string" || typeof body.refresh_token !== "string" || !body.refresh_token || typeof body.refresh_token_expires_at !== "string") return {
3781
+ const refreshResponse = CLI_AUTH_REFRESH_RESPONSE_SCHEMA.safeParse(body);
3782
+ if (!refreshResponse.success || refreshResponse.data.token_type.toLowerCase() !== "bearer") return {
3164
3783
  ok: false,
3165
3784
  error: validationError("Refresh response was invalid.", "Run login again. If this repeats, report the response shape.", "service_error")
3166
3785
  };
3167
3786
  const { pending_rotation_id: _completedRotation, ...persistedCredential } = stored.credential;
3787
+ const rotatingResponse = "refresh_token" in refreshResponse.data ? refreshResponse.data : null;
3788
+ const nextRefreshToken = rotatingResponse ? rotatingResponse.refresh_token : stored.credential.refresh_token;
3168
3789
  if (!(await saveProfileSessionCredential(profile, {
3169
3790
  ...persistedCredential,
3170
3791
  kind: "session",
3171
- session_token: body.access_token,
3172
- refresh_token: body.refresh_token,
3173
- expires_at: body.expires_at,
3174
- refresh_credential_expires_at: body.refresh_token_expires_at
3792
+ session_token: refreshResponse.data.access_token,
3793
+ refresh_token: nextRefreshToken,
3794
+ expires_at: refreshResponse.data.expires_at,
3795
+ ...rotatingResponse ? { refresh_credential_expires_at: rotatingResponse.refresh_token_expires_at } : {}
3175
3796
  }, options)).ok) return {
3176
3797
  ok: false,
3177
3798
  error: tokenStoreUnavailableError(profile, "store_operation_failed")
3178
3799
  };
3179
3800
  return {
3180
3801
  ok: true,
3181
- token: body.access_token
3802
+ token: refreshResponse.data.access_token
3182
3803
  };
3183
3804
  }
3184
3805
  async function handleJsonPendingAuth(command, credential, options, mode, rerun) {
@@ -4250,7 +4871,8 @@ function createPreviewStore(annotationsPath) {
4250
4871
  async function fetchProjects(token, options, init, errorOptions = {}) {
4251
4872
  const result = await apiGet("/api/cli/projects", token, options, init, errorOptions);
4252
4873
  if (result.error) return { error: result.error };
4253
- return { projects: (Array.isArray(result.body?.projects) ? result.body.projects : []).filter(isRecord$1).flatMap((project) => {
4874
+ const contracted = PROJECTS_LIST_RESPONSE_SCHEMA.safeParse(result.body);
4875
+ return { projects: (contracted.success ? contracted.data.projects : isRecord$1(result.body) && Array.isArray(result.body.projects) ? result.body.projects : []).filter(isRecord$1).flatMap((project) => {
4254
4876
  const id = configString(project.id);
4255
4877
  if (!id) return [];
4256
4878
  return [{
@@ -4318,7 +4940,9 @@ async function runProjectsCreate(parsed, mode) {
4318
4940
  return created.error ? { error: created.error } : { data: created.body };
4319
4941
  });
4320
4942
  if (result.error) return writeFailure(command, result.error, mode, 1);
4321
- const project = isRecord$1(result.data?.project) ? result.data.project : null;
4943
+ const contracted = PROJECT_CREATE_RESPONSE_SCHEMA.safeParse(result.data);
4944
+ const rawProject = isRecord$1(result.data) ? result.data.project : void 0;
4945
+ const project = contracted.success ? contracted.data.project : isRecord$1(rawProject) ? rawProject : null;
4322
4946
  const id = configString(project?.id);
4323
4947
  if (!id) return writeFailure(command, serviceError("Project create succeeded but no project id was returned."), mode, 1);
4324
4948
  writeSuccess(command, {
@@ -4406,6 +5030,11 @@ function normalizedEmailOptions$1(value) {
4406
5030
  return { values };
4407
5031
  }
4408
5032
  function parseProjectsEditData(body) {
5033
+ const contracted = PROJECT_EDIT_RESPONSE_SCHEMA.safeParse(body);
5034
+ if (contracted.success) return {
5035
+ project: contracted.data.project,
5036
+ audience: contracted.data.audience
5037
+ };
4409
5038
  if (!isRecord$1(body) || !isRecord$1(body.project)) return null;
4410
5039
  const { project } = body;
4411
5040
  if (typeof project.id !== "string" || typeof project.archived !== "boolean" || !Array.isArray(body.audience) || body.audience.some((email) => typeof email !== "string")) return null;
@@ -4436,20 +5065,25 @@ async function postShareUpload(args, baseUrl, fallbackKind) {
4436
5065
  if ("networkError" in response) return { error: networkError(response.networkError) };
4437
5066
  const body = await readJson(response);
4438
5067
  if (!response.ok) return { error: mapApiError(response.status, body, args.errorOptions) };
4439
- const id = body?.id ?? null;
4440
- const url = body?.shareUrl ?? (id ? `${baseUrl.replace(/\/$/, "")}/a/${id}` : null);
4441
- const warnings = Array.isArray(body?.warnings) ? body.warnings.flatMap((warning) => warning?.code === "slack_reauthorization_required" && typeof warning.message === "string" ? [{
4442
- code: "slack_reauthorization_required",
4443
- message: warning.message
4444
- }] : []) : [];
5068
+ const contractBody = isContract(ARTIFACT_UPLOAD_RESPONSE_SCHEMA, body) ? body : null;
5069
+ const recordBody = isRecord$1(body) ? body : null;
5070
+ const id = contractBody?.id ?? (typeof recordBody?.id === "string" ? recordBody.id : null);
5071
+ const url = contractBody?.shareUrl ?? (typeof recordBody?.shareUrl === "string" ? recordBody.shareUrl : id ? `${baseUrl.replace(/\/$/, "")}/a/${id}` : null);
5072
+ const warnings = contractBody?.warnings ? contractBody.warnings : Array.isArray(recordBody?.warnings) ? recordBody.warnings.flatMap((warning) => {
5073
+ if (!isRecord$1(warning)) return [];
5074
+ return warning.code === "slack_reauthorization_required" && typeof warning.message === "string" ? [{
5075
+ code: "slack_reauthorization_required",
5076
+ message: warning.message
5077
+ }] : [];
5078
+ }) : [];
4445
5079
  return { body: {
4446
5080
  id,
4447
5081
  url,
4448
- versionId: body?.versionId ?? null,
4449
- artifactKind: body?.artifactKind ?? fallbackKind,
4450
- visibility: body?.visibility ?? null,
4451
- linkExpiresAt: body?.link_expires_at ?? null,
4452
- created: body?.created ?? true,
5082
+ versionId: contractBody?.versionId ?? (typeof recordBody?.versionId === "string" ? recordBody.versionId : null),
5083
+ artifactKind: contractBody?.artifactKind ?? (typeof recordBody?.artifactKind === "string" ? recordBody.artifactKind : fallbackKind),
5084
+ visibility: contractBody?.visibility ?? (typeof recordBody?.visibility === "string" ? recordBody.visibility : null),
5085
+ linkExpiresAt: contractBody?.link_expires_at ?? (typeof recordBody?.link_expires_at === "string" || recordBody?.link_expires_at === null ? recordBody.link_expires_at : null),
5086
+ created: contractBody?.created ?? (typeof recordBody?.created === "boolean" ? recordBody.created : true),
4453
5087
  warnings
4454
5088
  } };
4455
5089
  }
@@ -4537,7 +5171,7 @@ const PREVIEW_MESSAGES = {
4537
5171
  "preview.shareDialog.shareFailed": "Sharing failed. Try again in a moment.",
4538
5172
  "preview.shareDialog.errorTokenInvalid": "The saved credential is no longer valid. Log in again, then reopen this dialog.",
4539
5173
  "preview.shareDialog.errorTokenInvalidExplicit": "The token supplied to this preview is invalid or expired. Stop the preview and start it again with a valid token.",
4540
- "preview.shareDialog.errorUploadNotAllowed": "Sharing is temporarily unavailable. Try again later.",
5174
+ "preview.shareDialog.errorSelfUploadDisabled": "This account cannot upload its own files. Sign in with Google or Microsoft to share files.",
4541
5175
  "preview.shareDialog.errorWorkspaceAccessRevoked": "This account no longer has access to that workspace.",
4542
5176
  "preview.shareDialog.errorStorageLimit": "The workspace has reached its storage limit.",
4543
5177
  "preview.shareDialog.snapshotFailed": "The file could not be read, so sharing is disabled. Reopen this dialog once it is available."
@@ -4623,7 +5257,7 @@ const PREVIEW_MESSAGES = {
4623
5257
  "preview.shareDialog.shareFailed": "共有に失敗しました。少し時間をおいて再試行してください。",
4624
5258
  "preview.shareDialog.errorTokenInvalid": "保存された認証情報が無効になりました。ログインし直してから、このダイアログを開き直してください。",
4625
5259
  "preview.shareDialog.errorTokenInvalidExplicit": "このプレビューに渡されたトークンが無効か期限切れです。プレビューを終了し、有効なトークンで起動し直してください。",
4626
- "preview.shareDialog.errorUploadNotAllowed": "現在共有できません。時間をおいて再試行してください。",
5260
+ "preview.shareDialog.errorSelfUploadDisabled": "このアカウントではファイルをアップロードできません。Google または Microsoft でログインして共有してください。",
4627
5261
  "preview.shareDialog.errorWorkspaceAccessRevoked": "このアカウントはそのワークスペースにアクセスできなくなりました。",
4628
5262
  "preview.shareDialog.errorStorageLimit": "ワークスペースの保存容量の上限に達しています。",
4629
5263
  "preview.shareDialog.snapshotFailed": "ファイルを読み取れないため共有できません。読み取れるようになってからこのダイアログを開き直してください。"
@@ -5315,7 +5949,7 @@ function renderPage(options) {
5315
5949
  var SHARE_ERROR_KEYS = {
5316
5950
  token_invalid: 'errorTokenInvalid',
5317
5951
  bot_token_invalid: 'errorTokenInvalid',
5318
- upload_not_allowed: 'errorUploadNotAllowed',
5952
+ self_upload_disabled: 'errorSelfUploadDisabled',
5319
5953
  workspace_access_revoked: 'errorWorkspaceAccessRevoked',
5320
5954
  storage_limit_exceeded: 'errorStorageLimit',
5321
5955
  };
@@ -5520,6 +6154,7 @@ const VIOLATION_REPORTER_TAG = `<script>${`(function () {
5520
6154
  var hasAttribute = Function.prototype.call.bind(Element.prototype.hasAttribute);
5521
6155
  var documentToken = '';
5522
6156
  var readyChallenge = '';
6157
+ var externalLinkPolicyMode = 'parent';
5523
6158
  var pendingLinkClicks = new WeakMap();
5524
6159
  function trusted(event) {
5525
6160
  try {
@@ -5747,7 +6382,7 @@ const VIOLATION_REPORTER_TAG = `<script>${`(function () {
5747
6382
  if (!pending) return;
5748
6383
  weakMapDelete(pendingLinkClicks, event);
5749
6384
  if (pending.artifactPrevented) return;
5750
- if (pending.openExternally) {
6385
+ if (pending.openExternally && externalLinkPolicyMode === 'direct') {
5751
6386
  openExternalLink(pending.href);
5752
6387
  return;
5753
6388
  }
@@ -7004,6 +7639,11 @@ const VIOLATION_REPORTER_TAG = `<script>${`(function () {
7004
7639
  onReadyCheck(event);
7005
7640
  textAnchorsEnabled = data.textAnchorsEnabled === true;
7006
7641
  setCommentLabels(data.commentLabels);
7642
+ } else if (
7643
+ data.kind === 'external-link-policy' &&
7644
+ (data.mode === 'parent' || data.mode === 'direct')
7645
+ ) {
7646
+ externalLinkPolicyMode = data.mode;
7007
7647
  } else if (data.kind === 'comment-highlights') {
7008
7648
  textAnchorsEnabled = data.textAnchorsEnabled === true;
7009
7649
  setCommentLabels(data.commentLabels);
@@ -7100,8 +7740,8 @@ function injectReadyReporter(html) {
7100
7740
  return `${html.slice(0, insertionPoint)}${VIOLATION_REPORTER_TAG}${html.slice(insertionPoint)}`;
7101
7741
  }
7102
7742
  //#endregion
7103
- //#region ../../node_modules/.pnpm/@tanstack+markdown@0.0.13_react@19.2.8/node_modules/@tanstack/markdown/dist/utils.js
7104
- const htmlEscapes = {
7743
+ //#region ../../node_modules/.pnpm/@tanstack+markdown@0.0.14_react@19.3.0/node_modules/@tanstack/markdown/dist/utils.js
7744
+ const htmlEscapes$1 = {
7105
7745
  "&": "&amp;",
7106
7746
  "<": "&lt;",
7107
7747
  ">": "&gt;",
@@ -7112,7 +7752,7 @@ function normalizeInput(value) {
7112
7752
  return value.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n");
7113
7753
  }
7114
7754
  function escapeHtml$5(value) {
7115
- return value.replace(/[&<>"']/g, (char) => htmlEscapes[char]);
7755
+ return value.replace(/[&<>"']/g, (char) => htmlEscapes$1[char]);
7116
7756
  }
7117
7757
  function escapeAttr(value) {
7118
7758
  return escapeHtml$5(value).replace(/`/g, "&#96;");
@@ -7132,41 +7772,58 @@ function plainText$1(nodes) {
7132
7772
  else if (node.type === "image") value += node.alt;
7133
7773
  return value;
7134
7774
  }
7135
- function createSlugger() {
7775
+ function createSlugger(normalize = headingSlug) {
7136
7776
  const seen = /* @__PURE__ */ new Map();
7137
7777
  return (value) => {
7138
- const base = value.toLowerCase().normalize("NFKD").replace(/[\u0300-\u036f]/g, "").replace(/&[a-z0-9#]+;/gi, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "section";
7139
- const count = seen.get(base) ?? 0;
7140
- seen.set(base, count + 1);
7141
- return count === 0 ? base : `${base}-${count + 1}`;
7778
+ const base = normalize(value);
7779
+ let count = seen.get(base) ?? 1;
7780
+ let id = base;
7781
+ while (seen.has(id)) id = `${base}-${++count}`;
7782
+ seen.set(base, count);
7783
+ seen.set(id, 1);
7784
+ return id;
7142
7785
  };
7143
7786
  }
7787
+ function headingSlug(value) {
7788
+ return value.toLowerCase().normalize("NFKD").replace(/[\u0300-\u036f]/g, "").replace(/&[a-z0-9#]+;/gi, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "section";
7789
+ }
7144
7790
  function sanitizeUrl(value) {
7145
- const trimmed = value.trim().replace(/[\u0000-\u001F\u007F\s]+/g, "");
7146
- if (!trimmed) return "";
7147
- if (/^(#|\/|\.\/|\.\.\/)/.test(trimmed)) return trimmed;
7148
- if (/^(https?:|mailto:|tel:)/i.test(trimmed)) return trimmed;
7149
- if (/^[a-z][a-z0-9+.-]*:/i.test(trimmed)) return "";
7150
- return trimmed;
7791
+ const trimmed = value.replace(/[\u0000-\u001F\u007F\s]+/g, "");
7792
+ return /^(?!https?:|mailto:|tel:)[a-z][a-z0-9+.-]*:/i.test(trimmed) ? "" : trimmed;
7793
+ }
7794
+ function parseDestination(value) {
7795
+ const match = value.match(/^(?:<([^<>\n]*)>|([^<>\s]*?))(?:\s+(?:"([^"]*)"|'([^']*)'|\(([^)]*)\)))?$/);
7796
+ if (!match) return void 0;
7797
+ const href = match[1] ?? match[2];
7798
+ const title = match[3] ?? match[4] ?? match[5];
7799
+ return {
7800
+ href: href.replace(/\\([!-/:-@\[-`{-~])/g, "$1"),
7801
+ ...title ? { title } : {}
7802
+ };
7151
7803
  }
7152
7804
  function normalizeReferenceLabel(value) {
7153
- return value.trim().toLowerCase();
7805
+ return value.trim().replace(/\s+/g, " ").toLowerCase();
7154
7806
  }
7155
7807
  function footnoteId(label) {
7156
- return normalizeReferenceLabel(label).replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
7808
+ return normalizeReferenceLabel(label).replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "") || "footnote";
7809
+ }
7810
+ function footnoteReferenceId(id, index = 1) {
7811
+ return index > 1 ? `${id}-${index}` : id;
7157
7812
  }
7158
7813
  //#endregion
7159
- //#region ../../node_modules/.pnpm/@tanstack+markdown@0.0.13_react@19.2.8/node_modules/@tanstack/markdown/dist/inline.js
7814
+ //#region ../../node_modules/.pnpm/@tanstack+markdown@0.0.14_react@19.3.0/node_modules/@tanstack/markdown/dist/inline.js
7160
7815
  function parseInline(value, options = {}) {
7161
- let result = mergeText(parseInlineRaw(value, options));
7816
+ let result = parseInlineRaw(value, options);
7162
7817
  for (const extension of options.extensions ?? []) result = extension.transformInline?.(result, { options }) ?? result;
7163
7818
  return result;
7164
7819
  }
7165
7820
  const maxInlineDepth = 32;
7166
7821
  const scansPerCharacter = 16;
7822
+ const inlineMarker = /[\\`!\[_*~<]/g;
7167
7823
  function parseInlineRaw(value, options, budget = {
7168
7824
  scans: Math.max(value.length * scansPerCharacter, 1024),
7169
- depth: 0
7825
+ depth: 0,
7826
+ links: 0
7170
7827
  }) {
7171
7828
  if (budget.depth >= maxInlineDepth) return value ? [{
7172
7829
  type: "text",
@@ -7195,7 +7852,7 @@ function parseInlineRaw(value, options, budget = {
7195
7852
  index += 2;
7196
7853
  continue;
7197
7854
  }
7198
- if (next && /[\\`*_[\]{}()#+\-.!|~<>]/.test(next)) {
7855
+ if (next && /[!-/:-@\[-`{-~]/.test(next)) {
7199
7856
  text += next;
7200
7857
  index += 2;
7201
7858
  continue;
@@ -7208,7 +7865,7 @@ function parseInlineRaw(value, options, budget = {
7208
7865
  pushText();
7209
7866
  nodes.push({
7210
7867
  type: "inlineCode",
7211
- value: value.slice(index + tickCount, close).replace(/\s+/g, " ").trim()
7868
+ value: value.slice(index + tickCount, close).replace(/\n/g, " ").replace(/^ (?! *$)(.*) $/s, "$1")
7212
7869
  });
7213
7870
  index = close + tickCount;
7214
7871
  continue;
@@ -7217,40 +7874,46 @@ function parseInlineRaw(value, options, budget = {
7217
7874
  index += tickCount;
7218
7875
  continue;
7219
7876
  }
7220
- if (char === "!" && next === "[") {
7221
- const parsed = parseLinkish(value, index + 1, options, budget);
7222
- if (parsed) {
7223
- pushText();
7224
- nodes.push({
7225
- type: "image",
7226
- src: sanitizeUrl(parsed.href),
7227
- alt: textFromMarkdown(parsed.label, budget),
7228
- ...parsed.title ? { title: parsed.title } : {}
7229
- });
7230
- index = parsed.end;
7231
- continue;
7232
- }
7233
- }
7234
- if (char === "[") {
7235
- const footnote = parseFootnoteReference(value, index, options, budget);
7877
+ if (char === "[" || char === "!" && next === "[") {
7878
+ const image = char === "!";
7879
+ const footnote = next === "^" && parseFootnoteReference(value, index, options, budget);
7236
7880
  if (footnote) {
7237
7881
  pushText();
7238
7882
  nodes.push(footnote.node);
7883
+ budget.links++;
7239
7884
  index = footnote.end;
7240
7885
  continue;
7241
7886
  }
7242
- const parsed = parseLinkish(value, index, options, budget);
7887
+ const parsed = parseLinkish(value, index + Number(image), options, budget);
7243
7888
  if (parsed) {
7889
+ const links = budget.links;
7890
+ const children = parseInlineRaw(parsed.label, image ? options.references ? { references: options.references } : {} : options, budget);
7891
+ const nested = !image && budget.links !== links;
7244
7892
  const href = sanitizeUrl(parsed.href);
7245
- pushText();
7246
- if (href) nodes.push({
7247
- type: "link",
7248
- href,
7249
- ...parsed.title ? { title: parsed.title } : {},
7250
- children: parseInlineRaw(parsed.label, options, budget)
7251
- });
7252
- else nodes.push(...parseInlineRaw(parsed.label, options, budget));
7253
- index = parsed.end;
7893
+ if (image || !nested && (href || !parsed.href)) {
7894
+ pushText();
7895
+ nodes.push({
7896
+ ...image ? {
7897
+ type: "image",
7898
+ src: href,
7899
+ alt: plainText$1(children)
7900
+ } : {
7901
+ type: "link",
7902
+ href,
7903
+ children
7904
+ },
7905
+ ...parsed.title ? { title: parsed.title } : {}
7906
+ });
7907
+ } else {
7908
+ if (nested) text += "[";
7909
+ for (const child of children) if (child.type === "text") text += child.value;
7910
+ else {
7911
+ pushText();
7912
+ nodes.push(child);
7913
+ }
7914
+ }
7915
+ budget.links = image ? links : budget.links + 1;
7916
+ index = nested ? index + parsed.label.length + 1 : parsed.end;
7254
7917
  continue;
7255
7918
  }
7256
7919
  }
@@ -7266,66 +7929,28 @@ function parseInlineRaw(value, options, budget = {
7266
7929
  continue;
7267
7930
  }
7268
7931
  }
7269
- if (char === "*" && next === "*" || char === "_" && next === "_") {
7270
- const close = char === "_" && !canUseUnderscore(value, index, 2, true) ? -1 : findDelimiter(value, index + 2, char + char, budget);
7271
- if (close !== -1) {
7272
- pushText();
7273
- nodes.push({
7274
- type: "strong",
7275
- children: parseInlineRaw(value.slice(index + 2, close), options, budget)
7276
- });
7277
- index = close + 2;
7278
- continue;
7279
- }
7280
- text += char + next;
7281
- index += 2;
7282
- continue;
7283
- }
7284
7932
  if (char === "~" && next === "~" && value[index + 2] === "~") {
7285
7933
  const run = countRun(value, index, "~");
7286
7934
  text += value.slice(index, index + run);
7287
7935
  index += run;
7288
7936
  continue;
7289
7937
  }
7290
- if (char === "~" && next === "~") {
7291
- const close = findDelimiter(value, index + 2, "~~", budget);
7938
+ if (char === "*" || char === "_" || char === "~") {
7939
+ const size = next === char ? 2 : 1;
7940
+ const close = char === "_" && !canUseUnderscore(value, index, size, true) ? -1 : findDelimiter(value, index + size, char.repeat(size), budget);
7292
7941
  if (close !== -1) {
7293
7942
  pushText();
7294
7943
  nodes.push({
7295
- type: "strike",
7296
- children: parseInlineRaw(value.slice(index + 2, close), options, budget)
7944
+ type: char === "~" ? "strike" : size === 2 ? "strong" : "emphasis",
7945
+ children: parseInlineRaw(value.slice(index + size, close), options, budget)
7297
7946
  });
7298
- index = close + 2;
7299
- continue;
7947
+ index = close + size;
7948
+ } else {
7949
+ text += char.repeat(size);
7950
+ index += size;
7300
7951
  }
7301
- text += "~~";
7302
- index += 2;
7303
7952
  continue;
7304
7953
  }
7305
- if (char === "~") {
7306
- const close = findSingleTildeDelimiter(value, index + 1, budget);
7307
- if (close !== -1) {
7308
- pushText();
7309
- nodes.push({
7310
- type: "strike",
7311
- children: parseInlineRaw(value.slice(index + 1, close), options, budget)
7312
- });
7313
- index = close + 1;
7314
- continue;
7315
- }
7316
- }
7317
- if (char === "*" || char === "_") {
7318
- const close = char === "_" && !canUseUnderscore(value, index, 1, true) ? -1 : findDelimiter(value, index + 1, char, budget);
7319
- if (close !== -1) {
7320
- pushText();
7321
- nodes.push({
7322
- type: "emphasis",
7323
- children: parseInlineRaw(value.slice(index + 1, close), options, budget)
7324
- });
7325
- index = close + 1;
7326
- continue;
7327
- }
7328
- }
7329
7954
  if (char === "<" && options.allowHtml) {
7330
7955
  const close = findCharacter(value, index + 1, ">", budget);
7331
7956
  if (close !== -1 && isInlineHtml(value.slice(index, close + 1))) {
@@ -7338,32 +7963,30 @@ function parseInlineRaw(value, options, budget = {
7338
7963
  continue;
7339
7964
  }
7340
7965
  }
7341
- text += char;
7342
- index++;
7966
+ inlineMarker.lastIndex = index + 1;
7967
+ const end = budget.scans > 0 ? inlineMarker.exec(value)?.index ?? value.length : value.indexOf("\\", index + 1);
7968
+ text += value.slice(index, end < 0 ? value.length : end);
7969
+ index = end < 0 ? value.length : end;
7343
7970
  }
7344
7971
  pushText();
7345
7972
  budget.depth--;
7346
7973
  return nodes;
7347
7974
  }
7348
7975
  function parseFootnoteReference(value, open, options, budget) {
7349
- if (value[open + 1] !== "^") return void 0;
7350
7976
  const close = findCharacter(value, open + 2, "]", budget);
7351
7977
  if (close === -1) return void 0;
7352
7978
  const key = normalizeReferenceLabel(value.slice(open + 2, close));
7353
7979
  const definition = options.footnotes?.[key];
7354
7980
  if (!definition || !options.footnoteOrder) return void 0;
7355
- let orderIndex = options.footnoteOrder.indexOf(key);
7356
- if (orderIndex === -1) {
7357
- options.footnoteOrder.push(key);
7358
- orderIndex = options.footnoteOrder.length - 1;
7359
- }
7981
+ let number = options.footnoteOrder.indexOf(key) + 1;
7982
+ if (!number) number = options.footnoteOrder.push(key);
7360
7983
  const referenceIndex = (options.footnoteCounts?.[key] ?? 0) + 1;
7361
7984
  if (options.footnoteCounts) options.footnoteCounts[key] = referenceIndex;
7362
7985
  return {
7363
7986
  node: {
7364
7987
  type: "footnoteReference",
7365
- id: definition.id ?? (footnoteId(definition.label) || "footnote"),
7366
- number: orderIndex + 1,
7988
+ id: definition.id ?? footnoteId(definition.label),
7989
+ number,
7367
7990
  ...referenceIndex > 1 ? { referenceIndex } : {}
7368
7991
  },
7369
7992
  end: close + 1
@@ -7373,58 +7996,37 @@ function parseLinkish(value, open, options, budget) {
7373
7996
  const closeBracket = findBalanced(value, open, "[", "]", budget);
7374
7997
  if (closeBracket === -1) return void 0;
7375
7998
  const label = value.slice(open + 1, closeBracket);
7376
- if (value[closeBracket + 1] === "(") {
7377
- const closeParen = findBalanced(value, closeBracket + 1, "(", ")", budget);
7999
+ let end = closeBracket + 1;
8000
+ let definition;
8001
+ if (value[end] === "(") {
8002
+ const closeParen = findBalanced(value, end, "(", ")", budget);
7378
8003
  if (closeParen === -1) return void 0;
7379
- const parsed = parseDestination(value.slice(closeBracket + 2, closeParen).trim());
7380
- if (!parsed) return void 0;
7381
- return {
7382
- label,
7383
- href: parsed.href,
7384
- ...parsed.title ? { title: parsed.title } : {},
7385
- end: closeParen + 1
7386
- };
7387
- }
7388
- if (value[closeBracket + 1] === "[") {
7389
- const closeReference = findBalanced(value, closeBracket + 1, "[", "]", budget);
8004
+ definition = parseDestination(value.slice(end + 1, closeParen).trim());
8005
+ end = closeParen + 1;
8006
+ } else if (value[end] === "[") {
8007
+ const closeReference = findBalanced(value, end, "[", "]", budget);
7390
8008
  if (closeReference === -1) return void 0;
7391
- const referenceLabel = value.slice(closeBracket + 2, closeReference);
7392
- const definition = options.references?.[normalizeReferenceLabel(referenceLabel || label)];
7393
- if (!definition) return void 0;
7394
- return {
7395
- label,
7396
- href: definition.href,
7397
- ...definition.title ? { title: definition.title } : {},
7398
- end: closeReference + 1
7399
- };
7400
- }
7401
- const definition = options.references?.[normalizeReferenceLabel(label)];
8009
+ definition = options.references?.[normalizeReferenceLabel(value.slice(end + 1, closeReference) || label)];
8010
+ end = closeReference + 1;
8011
+ } else definition = options.references?.[normalizeReferenceLabel(label)];
7402
8012
  if (definition) return {
8013
+ ...definition,
7403
8014
  label,
7404
- href: definition.href,
7405
- ...definition.title ? { title: definition.title } : {},
7406
- end: closeBracket + 1
8015
+ end
7407
8016
  };
7408
8017
  }
7409
8018
  function isInlineHtml(value) {
7410
- if (/^<!--(?:[\s\S]*--|-?)>$/.test(value)) return true;
7411
- if (/^<\?[\s\S]*\?>$/.test(value) || /^<![A-Z][\s\S]*>$/.test(value) || /^<!\[CDATA\[[\s\S]*\]\]>$/.test(value)) return true;
7412
- if (/^<\/[A-Za-z][\w:-]*\s*>$/.test(value)) return true;
7413
- return /^<[A-Za-z][\w:-]*(?:\s+[A-Za-z_:][\w:.-]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*\s*\/?>$/.test(value);
7414
- }
7415
- function parseDestination(value) {
7416
- const match = value.match(/^(\S+)(?:\s+["']([^"']*)["'])?$/);
7417
- if (!match) return { href: value };
7418
- return {
7419
- href: match[1].replace(/^<|>$/g, ""),
7420
- ...match[2] ? { title: match[2] } : {}
7421
- };
8019
+ return /^<(?:!--(?:[\s\S]*--|-?)|\?[\s\S]*\?|![A-Z][\s\S]*|!\[CDATA\[[\s\S]*\]\]|\/[A-Za-z][\w:-]*\s*|[A-Za-z][\w:-]*(?:\s+[A-Za-z_:][\w:.-]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*\s*\/?)>$/.test(value);
7422
8020
  }
7423
8021
  function findBalanced(value, openIndex, open, close, budget) {
8022
+ if (findCharacter(value, openIndex + 1, close, budget) === -1) return -1;
7424
8023
  let depth = 0;
7425
8024
  for (let index = openIndex; index < value.length; index++) {
7426
- if (!takeScan(budget)) return -1;
7427
- if (value[index - 1] === "\\") continue;
8025
+ if (--budget.scans < 0) return -1;
8026
+ if (value[index] === "\\") {
8027
+ index++;
8028
+ continue;
8029
+ }
7428
8030
  if (value[index] === open) depth++;
7429
8031
  if (value[index] === close) {
7430
8032
  depth--;
@@ -7436,92 +8038,58 @@ function findBalanced(value, openIndex, open, close, budget) {
7436
8038
  function countRun(value, index, char, budget) {
7437
8039
  let count = 0;
7438
8040
  while (value[index + count] === char) {
7439
- if (budget && !takeScan(budget)) break;
8041
+ if (budget && --budget.scans < 0) break;
7440
8042
  count++;
7441
8043
  }
7442
8044
  return count;
7443
8045
  }
7444
8046
  function findClosingRun(value, start, char, count, budget) {
7445
- for (let index = start; index < value.length; index++) {
7446
- if (!takeScan(budget)) return -1;
7447
- if (value[index] !== char) continue;
7448
- if (countRun(value, index, char, budget) >= count) return index;
8047
+ let index = start;
8048
+ while ((index = findCharacter(value, index, char, budget)) !== -1) {
8049
+ const size = countRun(value, index, char, budget);
8050
+ if (size === count) return index;
8051
+ index += size;
7449
8052
  }
7450
8053
  return -1;
7451
8054
  }
7452
8055
  function findDelimiter(value, start, delimiter, budget) {
8056
+ if (delimiter === "~" && /[\s\d]/.test(value[start] ?? "")) return -1;
7453
8057
  for (let index = start; index < value.length; index++) {
7454
- if (!takeScan(budget)) return -1;
7455
- if (value[index - 1] === "\\") continue;
8058
+ if (--budget.scans < 0) return -1;
8059
+ if (value[index] === "\\") {
8060
+ index++;
8061
+ continue;
8062
+ }
7456
8063
  if (!value.startsWith(delimiter, index)) continue;
7457
- if (value[index + 1] === delimiter) {
7458
- const close = findDelimiter(value, index + 2, delimiter + delimiter, budget);
7459
- if (close > index + 2) {
7460
- index = close + 1;
8064
+ if (delimiter[0] === "~") {
8065
+ if (value[index - 1] === "~" || value[index + delimiter.length] === "~") continue;
8066
+ if (delimiter === "~" && /\s/.test(value[index - 1] ?? "")) return -1;
8067
+ } else if (value[index + 1] === delimiter) {
8068
+ const size = countRun(value, index, delimiter, budget);
8069
+ const close = findDelimiter(value, index + size, delimiter.repeat(size), budget);
8070
+ if (close > index + size) {
8071
+ index = close + size - 1;
7461
8072
  continue;
7462
8073
  }
7463
8074
  }
7464
- if (delimiter === "~~" && (value[index - 1] === "~" || value[index + 2] === "~")) continue;
7465
8075
  if (delimiter[0] === "_" && !canUseUnderscore(value, index, delimiter.length, false)) continue;
7466
8076
  return index;
7467
8077
  }
7468
8078
  return -1;
7469
8079
  }
7470
- function findSingleTildeDelimiter(value, start, budget) {
7471
- if (isWhitespace(value[start] ?? "") || /\d/.test(value[start] ?? "")) return -1;
7472
- for (let index = start; index < value.length; index++) {
7473
- if (!takeScan(budget)) return -1;
7474
- if (value[index - 1] === "\\") continue;
7475
- if (value[index] !== "~") continue;
7476
- if (value[index - 1] === "~") continue;
7477
- if (value[index + 1] === "~") continue;
7478
- if (isWhitespace(value[index - 1] ?? "")) return -1;
7479
- return index;
7480
- }
7481
- return -1;
7482
- }
7483
8080
  function findCharacter(value, start, character, budget) {
7484
- for (let index = start; index < value.length; index++) {
7485
- if (!takeScan(budget)) return -1;
7486
- if (value[index] === character) return index;
7487
- }
7488
- return -1;
7489
- }
7490
- function takeScan(budget) {
7491
- if (budget.scans <= 0) return false;
7492
- budget.scans--;
7493
- return true;
8081
+ if (budget.scans <= 0) return -1;
8082
+ const index = value.indexOf(character, start);
8083
+ budget.scans -= (index < 0 ? value.length : index + 1) - start;
8084
+ return budget.scans < 0 ? -1 : index;
7494
8085
  }
7495
8086
  function canUseUnderscore(value, index, size, opening) {
7496
- const before = value[index - 1];
7497
- const after = value[index + size];
7498
- const leftFlanking = !isDelimiterWhitespace(after) && (!isPunctuation(after) || isDelimiterWhitespace(before) || isPunctuation(before));
7499
- const rightFlanking = !isDelimiterWhitespace(before) && (!isPunctuation(before) || isDelimiterWhitespace(after) || isPunctuation(after));
7500
- return opening ? leftFlanking && (!rightFlanking || isPunctuation(before)) : rightFlanking && (!leftFlanking || isPunctuation(after));
7501
- }
7502
- function isDelimiterWhitespace(value) {
7503
- return value === void 0 || /\s/.test(value);
7504
- }
7505
- function isPunctuation(value) {
7506
- return value !== void 0 && /[^\p{L}\p{N}\s]/u.test(value);
7507
- }
7508
- function isWhitespace(value) {
7509
- return /\s/.test(value);
7510
- }
7511
- function textFromMarkdown(value, budget) {
7512
- return parseInlineRaw(value, {}, budget).map((node) => node.type === "text" || node.type === "inlineCode" ? node.value : "").join("");
7513
- }
7514
- function mergeText(nodes) {
7515
- const result = [];
7516
- for (const node of nodes) {
7517
- const previous = result.at(-1);
7518
- if (previous?.type === "text" && node.type === "text") previous.value += node.value;
7519
- else result.push(node);
7520
- }
7521
- return result;
8087
+ const inside = value[opening ? index + size : index - 1];
8088
+ const outside = value[opening ? index - 1 : index + size];
8089
+ return inside !== void 0 && !/\s/.test(inside) && (outside === void 0 || /[^\p{L}\p{N}]/u.test(outside));
7522
8090
  }
7523
8091
  //#endregion
7524
- //#region ../../node_modules/.pnpm/@tanstack+markdown@0.0.13_react@19.2.8/node_modules/@tanstack/markdown/dist/parser.js
8092
+ //#region ../../node_modules/.pnpm/@tanstack+markdown@0.0.14_react@19.3.0/node_modules/@tanstack/markdown/dist/parser.js
7525
8093
  const maxBlockDepth = 64;
7526
8094
  function parseMarkdown(markdown, options = {}) {
7527
8095
  const normalized = normalizeInput(markdown);
@@ -7550,8 +8118,9 @@ function parseMarkdown(markdown, options = {}) {
7550
8118
  footnoteCounts
7551
8119
  } : {}
7552
8120
  } : options;
7553
- const children = new BlockParser(lines, parseOptions, createSlugger()).parse();
7554
- if (hasFootnotes && footnoteOrder.length > 0) children.push(createFootnotesBlock(definitions.footnotes, footnoteOrder, parseOptions));
8121
+ const slugger = createSlugger();
8122
+ const children = new BlockParser(lines, parseOptions, slugger).parse();
8123
+ if (hasFootnotes && footnoteOrder.length > 0) children.push(createFootnotesBlock(definitions.footnotes, footnoteOrder, parseOptions, slugger));
7555
8124
  let document = frontmatter === void 0 ? {
7556
8125
  type: "root",
7557
8126
  children
@@ -7569,6 +8138,7 @@ var BlockParser = class BlockParser {
7569
8138
  slugger;
7570
8139
  budget;
7571
8140
  index = 0;
8141
+ loose = false;
7572
8142
  constructor(lines, options, slugger, budget = { depth: 0 }) {
7573
8143
  this.lines = lines;
7574
8144
  this.options = options;
@@ -7588,6 +8158,7 @@ var BlockParser = class BlockParser {
7588
8158
  const nodes = [];
7589
8159
  while (this.index < this.lines.length) {
7590
8160
  if (isBlank(this.current())) {
8161
+ if (nodes.length) this.loose = true;
7591
8162
  this.index++;
7592
8163
  continue;
7593
8164
  }
@@ -7622,22 +8193,19 @@ var BlockParser = class BlockParser {
7622
8193
  }
7623
8194
  }
7624
8195
  parseFence() {
7625
- const match = this.current().match(/^ {0,3}(`{3,}|~{3,})(.*)$/);
8196
+ const match = this.current().match(/^( {0,3})(`{3,}|~{3,})(.*)$/);
7626
8197
  if (!match) return void 0;
7627
- const fence = match[1];
7628
- const marker = fence[0];
7629
- const fenceSize = fence.length;
7630
- const info = match[2].trim();
8198
+ const fence = match[2];
8199
+ const info = match[3].trim();
7631
8200
  const code = [];
7632
8201
  this.index++;
7633
8202
  while (this.index < this.lines.length) {
7634
8203
  const line = this.current();
7635
- const close = line.match(/^ {0,3}(`{3,}|~{3,})\s*$/);
7636
- if (close && close[1][0] === marker && close[1].length >= fenceSize) {
8204
+ if (line.match(/^ {0,3}(`{3,}|~{3,})\s*$/)?.[1].startsWith(fence)) {
7637
8205
  this.index++;
7638
8206
  break;
7639
8207
  }
7640
- code.push(line);
8208
+ code.push(stripIndent(line, match[1].length));
7641
8209
  this.index++;
7642
8210
  }
7643
8211
  return {
@@ -7675,14 +8243,12 @@ var BlockParser = class BlockParser {
7675
8243
  const quoted = [];
7676
8244
  while (this.index < this.lines.length) {
7677
8245
  const line = this.current();
7678
- if (isBlank(line)) {
7679
- quoted.push("");
7680
- this.index++;
7681
- continue;
7682
- }
7683
8246
  const match = line.match(/^ {0,3}>\s?(.*)$/);
7684
- if (!match) break;
7685
- quoted.push(match[1]);
8247
+ if (!match) {
8248
+ if (!isBlank(line)) break;
8249
+ this.loose = true;
8250
+ }
8251
+ quoted.push(match?.[1] ?? "");
7686
8252
  this.index++;
7687
8253
  }
7688
8254
  return {
@@ -7696,11 +8262,10 @@ var BlockParser = class BlockParser {
7696
8262
  const items = [];
7697
8263
  const ordered = first.ordered;
7698
8264
  const baseIndent = first.indent;
7699
- const start = ordered ? first.number : void 0;
7700
8265
  let loose = false;
7701
8266
  while (this.index < this.lines.length) {
7702
8267
  const marker = listMarker(this.current());
7703
- if (!marker || !sameListType(marker, first) || marker.indent !== baseIndent) break;
8268
+ if (!marker || marker.marker !== first.marker || marker.indent !== baseIndent) break;
7704
8269
  let firstLine = marker.content;
7705
8270
  const task = firstLine.match(/^\[([ xX])\]\s+(.*)$/);
7706
8271
  const checked = task ? task[1].toLowerCase() === "x" : void 0;
@@ -7718,15 +8283,13 @@ var BlockParser = class BlockParser {
7718
8283
  if (following === void 0) break;
7719
8284
  const followingMarker = listMarker(following);
7720
8285
  if (followingMarker?.indent === baseIndent) {
7721
- if (!sameListType(followingMarker, first)) break;
8286
+ if (followingMarker.marker !== first.marker) break;
7722
8287
  loose = true;
7723
8288
  this.index = nextIndex;
7724
8289
  break;
7725
8290
  }
7726
8291
  if (leadingSpaces(following) < marker.contentIndent) break;
7727
- loose = true;
7728
- itemLines.push("");
7729
- this.index = nextIndex;
8292
+ while (this.index < nextIndex) itemLines.push(stripIndent(this.lines[this.index++], marker.contentIndent));
7730
8293
  continue;
7731
8294
  }
7732
8295
  if (leadingSpaces(line) >= marker.contentIndent) {
@@ -7738,9 +8301,12 @@ var BlockParser = class BlockParser {
7738
8301
  itemLines.push(line.trimStart());
7739
8302
  this.index++;
7740
8303
  }
8304
+ const parser = new BlockParser(itemLines, this.options, this.slugger, this.budget);
8305
+ const children = parser.parse();
8306
+ loose ||= parser.loose;
7741
8307
  const item = {
7742
8308
  type: "listItem",
7743
- children: new BlockParser(itemLines, this.options, this.slugger, this.budget).parse()
8309
+ children
7744
8310
  };
7745
8311
  if (checked !== void 0) item.checked = checked;
7746
8312
  items.push(item);
@@ -7748,7 +8314,7 @@ var BlockParser = class BlockParser {
7748
8314
  return {
7749
8315
  type: "list",
7750
8316
  ordered,
7751
- ...ordered && start !== void 0 ? { start } : {},
8317
+ ...ordered && { start: first.number },
7752
8318
  ...loose && { loose: true },
7753
8319
  items
7754
8320
  };
@@ -7834,7 +8400,7 @@ function parseCodeInfo(info) {
7834
8400
  const titleMatch = meta.match(/(?:^|\s)(?:title|file)=(?:"([^"]+)"|'([^']+)'|([^\s}]+))/);
7835
8401
  const frameworkMatch = meta.match(/(?:^|\s)framework=(?:"([^"]+)"|'([^']+)'|([^\s}]+))/);
7836
8402
  const rangeMatch = meta.match(/\{([^}]+)\}|(?:^|\s)lines=([^\s]+)/);
7837
- const highlightLines = parseLineRanges(rangeMatch?.[1] ?? rangeMatch?.[2] ?? "");
8403
+ const highlightLines = rangeMatch ? parseLineRanges(rangeMatch[1] ?? rangeMatch[2]) : [];
7838
8404
  const title = titleMatch ? titleMatch[1] ?? titleMatch[2] ?? titleMatch[3] : void 0;
7839
8405
  const framework = frameworkMatch ? frameworkMatch[1] ?? frameworkMatch[2] ?? frameworkMatch[3] : void 0;
7840
8406
  return {
@@ -7851,28 +8417,17 @@ function parseCodeInfo(info) {
7851
8417
  function extractDefinitions(lines) {
7852
8418
  const references = Object.create(null);
7853
8419
  const footnotes = Object.create(null);
7854
- const footnoteIds = /* @__PURE__ */ new Map();
8420
+ const footnoteIds = createSlugger(footnoteId);
7855
8421
  const remaining = [];
7856
- let fenceMarker;
7857
- let fenceSize = 0;
8422
+ let activeFence = "";
7858
8423
  let index = 0;
7859
8424
  while (index < lines.length) {
7860
8425
  const line = lines[index];
7861
- const fence = line.match(/^ {0,3}(`{3,}|~{3,})/);
8426
+ const fence = line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/);
7862
8427
  if (fence) {
7863
- const marker = fence[1][0];
7864
- if (!fenceMarker) {
7865
- fenceMarker = marker;
7866
- fenceSize = fence[1].length;
7867
- } else if (marker === fenceMarker && fence[1].length >= fenceSize) {
7868
- fenceMarker = void 0;
7869
- fenceSize = 0;
7870
- }
7871
- remaining.push(line);
7872
- index++;
7873
- continue;
7874
- }
7875
- if (!fenceMarker) {
8428
+ if (!activeFence) activeFence = fence[1];
8429
+ else if (fence[1].startsWith(activeFence) && isBlank(fence[2])) activeFence = "";
8430
+ } else if (!activeFence) {
7876
8431
  const footnote = line.match(/^ {0,3}\[\^([^\]\n]+)\]:[ \t]*(.*)$/);
7877
8432
  if (footnote) {
7878
8433
  const label = footnote[1];
@@ -7885,25 +8440,17 @@ function extractDefinitions(lines) {
7885
8440
  index++;
7886
8441
  }
7887
8442
  const key = normalizeReferenceLabel(label);
7888
- if (!footnotes[key]) {
7889
- const baseId = footnoteId(label) || "footnote";
7890
- const count = (footnoteIds.get(baseId) ?? 0) + 1;
7891
- footnoteIds.set(baseId, count);
7892
- footnotes[key] = {
7893
- label,
7894
- content: content.join("\n"),
7895
- id: count === 1 ? baseId : `${baseId}-${count}`
7896
- };
7897
- }
8443
+ if (!footnotes[key]) footnotes[key] = {
8444
+ label,
8445
+ content: content.join("\n"),
8446
+ id: footnoteIds(label)
8447
+ };
7898
8448
  continue;
7899
8449
  }
7900
- const definition = line.match(/^ {0,3}\[([^\]\n]+)\]:[ \t]*(\S+)(?:[ \t]+(?:"([^"]*)"|'([^']*)'|\(([^)]*)\)))?[ \t]*$/);
7901
- if (definition) {
7902
- const title = definition[3] ?? definition[4] ?? definition[5];
7903
- references[normalizeReferenceLabel(definition[1])] = {
7904
- href: definition[2].replace(/^<|>$/g, ""),
7905
- ...title !== void 0 ? { title } : {}
7906
- };
8450
+ const definition = line.match(/^ {0,3}\[([^\]\n]+)\]:[ \t]*(\S.*)$/);
8451
+ const destination = definition && parseDestination(definition[2].trimEnd());
8452
+ if (destination) {
8453
+ references[normalizeReferenceLabel(definition[1])] ??= destination;
7907
8454
  index++;
7908
8455
  continue;
7909
8456
  }
@@ -7917,15 +8464,15 @@ function extractDefinitions(lines) {
7917
8464
  footnotes
7918
8465
  };
7919
8466
  }
7920
- function createFootnotesBlock(footnotes, footnoteOrder, options) {
8467
+ function createFootnotesBlock(footnotes, footnoteOrder, options, slugger) {
7921
8468
  const items = [];
7922
8469
  for (let index = 0; index < footnoteOrder.length; index++) {
7923
8470
  const definition = footnotes[footnoteOrder[index]];
7924
8471
  if (!definition) continue;
7925
8472
  items.push({
7926
- id: definition.id ?? (footnoteId(definition.label) || "footnote"),
8473
+ id: definition.id ?? footnoteId(definition.label),
7927
8474
  number: index + 1,
7928
- children: new BlockParser(normalizeInput(definition.content).split("\n"), options, createSlugger()).parse()
8475
+ children: new BlockParser(normalizeInput(definition.content).split("\n"), options, slugger).parse()
7929
8476
  });
7930
8477
  }
7931
8478
  for (const item of items) {
@@ -7944,6 +8491,7 @@ function parseLineRanges(value) {
7944
8491
  if (!match) continue;
7945
8492
  const start = Number(match[1]);
7946
8493
  const end = Number(match[2] ?? match[1]);
8494
+ if (end > Number.MAX_SAFE_INTEGER) continue;
7947
8495
  for (let line = start; line <= end && line < start + 1e3; line++) lines.add(line);
7948
8496
  }
7949
8497
  return [...lines].sort((a, b) => a - b);
@@ -7962,15 +8510,12 @@ function listMarker(line) {
7962
8510
  content: match[4] ?? ""
7963
8511
  };
7964
8512
  }
7965
- function sameListType(left, right) {
7966
- return left.ordered === right.ordered && left.marker === right.marker;
7967
- }
7968
8513
  function leadingSpaces(line) {
7969
8514
  return line.match(/^ */)?.[0].length ?? 0;
7970
8515
  }
7971
8516
  function isBlockStart(line, next) {
7972
8517
  const marker = listMarker(line);
7973
- return /^ {0,3}(`{3,}|~{3,})/.test(line) || /^ {0,3}#{1,6}(?:\s+|$)/.test(line) || /^ {0,3}([-*_])(?:\s*\1){2,}\s*$/.test(line) || /^ {0,3}>\s?/.test(line) || marker !== void 0 && (!marker.ordered || marker.number === 1) || !!next && looksLikeTableHeader(line, next);
8518
+ return /^ {0,3}(?:`{3,}|~{3,}|#{1,6}(?:\s|$)|([-*_])(?:\s*\1){2,}\s*$|>)/.test(line) || marker !== void 0 && (!marker.ordered || marker.number === 1) || !!next && looksLikeTableHeader(line, next);
7974
8519
  }
7975
8520
  function looksLikeTableHeader(header, delimiter) {
7976
8521
  if (!header.includes("|")) return false;
@@ -7978,12 +8523,10 @@ function looksLikeTableHeader(header, delimiter) {
7978
8523
  return cells.length === splitTableRow(header).length && cells.every((cell) => /^:?-+:?$/.test(cell.trim()));
7979
8524
  }
7980
8525
  function splitTableRow(value) {
7981
- let row = value.trim();
7982
- if (row.startsWith("|")) row = row.slice(1);
7983
- if (row.endsWith("|")) row = row.slice(0, -1);
8526
+ const row = value.trim();
7984
8527
  const cells = [];
7985
8528
  let current = "";
7986
- for (let index = 0; index < row.length; index++) {
8529
+ for (let index = row.startsWith("|") ? 1 : 0; index < row.length; index++) {
7987
8530
  const char = row[index];
7988
8531
  if (char === "\\" && row[index + 1] === "|") {
7989
8532
  current += "|";
@@ -7997,7 +8540,7 @@ function splitTableRow(value) {
7997
8540
  }
7998
8541
  current += char;
7999
8542
  }
8000
- cells.push(current.trim());
8543
+ if (current || !row.endsWith("|") || !cells.length) cells.push(current.trim());
8001
8544
  return cells;
8002
8545
  }
8003
8546
  function parseAlign(value) {
@@ -8013,7 +8556,7 @@ function cell(value, options) {
8013
8556
  };
8014
8557
  }
8015
8558
  //#endregion
8016
- //#region ../../node_modules/.pnpm/@tanstack+markdown@0.0.13_react@19.2.8/node_modules/@tanstack/markdown/dist/html.js
8559
+ //#region ../../node_modules/.pnpm/@tanstack+markdown@0.0.14_react@19.3.0/node_modules/@tanstack/markdown/dist/html.js
8017
8560
  function renderHtml(input, options = {}) {
8018
8561
  return (typeof input === "string" ? parseMarkdown(input, options) : input).children.map((node) => renderBlock(node, options)).join("\n");
8019
8562
  }
@@ -8030,7 +8573,7 @@ function renderBlock(node, options = {}) {
8030
8573
  case "code": return renderCodeBlock(node, options);
8031
8574
  case "list": {
8032
8575
  const tag = node.ordered ? "ol" : "ul";
8033
- return `<${tag}${node.ordered && node.start && node.start !== 1 ? ` start="${node.start}"` : ""}>\n${node.items.map((item) => `<li>${renderListItemChildren(item.children, item.checked, node.loose, options)}</li>`).join("\n")}\n</${tag}>`;
8576
+ return `<${tag}${node.ordered && node.start !== void 0 && node.start !== 1 ? ` start="${node.start}"` : ""}>\n${node.items.map((item) => `<li>${renderListItemChildren(item.children, item.checked, node.loose, options)}</li>`).join("\n")}\n</${tag}>`;
8034
8577
  }
8035
8578
  case "blockquote": return `<blockquote>\n${node.children.map((child) => renderBlock(child, options)).join("\n")}\n</blockquote>`;
8036
8579
  case "table": return `<table>${`<thead><tr>${node.header.map((cell, index) => renderTableCell("th", cell, node.align[index], options)).join("")}</tr></thead>`}${node.rows.length ? `<tbody>${node.rows.map((row) => `<tr>${row.map((cell, index) => renderTableCell("td", cell, node.align[index], options)).join("")}</tr>`).join("")}</tbody>` : ""}</table>`;
@@ -8050,7 +8593,7 @@ function renderInline(node, options = {}) {
8050
8593
  case "strong": return `<strong>${renderInlines(node.children, options)}</strong>`;
8051
8594
  case "emphasis": return `<em>${renderInlines(node.children, options)}</em>`;
8052
8595
  case "strike": return `<del>${renderInlines(node.children, options)}</del>`;
8053
- case "footnoteReference": return `<sup><a id="user-content-fnref-${escapeAttr(footnoteReferenceId(node))}" data-footnote-ref="" aria-describedby="footnote-label" href="#user-content-fn-${escapeAttr(node.id)}">${node.number}</a></sup>`;
8596
+ case "footnoteReference": return `<sup><a id="user-content-fnref-${escapeAttr(footnoteReferenceId(node.id, node.referenceIndex))}" data-footnote-ref="" aria-describedby="footnote-label" href="#user-content-fn-${escapeAttr(node.id)}">${node.number}</a></sup>`;
8054
8597
  case "link": return `<a href="${escapeAttr(node.href)}"${node.title ? ` title="${escapeAttr(node.title)}"` : ""}>${renderInlines(node.children, options)}</a>`;
8055
8598
  case "image": return `<img src="${escapeAttr(node.src)}" alt="${escapeAttr(node.alt)}"${node.title ? ` title="${escapeAttr(node.title)}"` : ""}>`;
8056
8599
  case "break": return "<br>";
@@ -8062,13 +8605,7 @@ function renderInlines(nodes, options) {
8062
8605
  }
8063
8606
  function renderCodeBlock(node, options) {
8064
8607
  const lang = node.lang ?? "plaintext";
8065
- const preAttrs = [
8066
- `class="tm-code${options.codeLineNumbers ? " tm-code--line-numbers" : ""}"`,
8067
- `data-lang="${escapeAttr(lang)}"`,
8068
- node.title ? `data-code-title="${escapeAttr(node.title)}"` : "",
8069
- node.file ? `data-filename="${escapeAttr(node.file)}"` : "",
8070
- node.framework ? `data-framework="${escapeAttr(node.framework)}"` : ""
8071
- ].filter(Boolean).join(" ");
8608
+ const preAttrs = `class="tm-code${options.codeLineNumbers ? " tm-code--line-numbers" : ""}" data-lang="${escapeAttr(lang)}"` + (node.title ? ` data-code-title="${escapeAttr(node.title)}"` : "") + (node.file ? ` data-filename="${escapeAttr(node.file)}"` : "") + (node.framework ? ` data-framework="${escapeAttr(node.framework)}"` : "");
8072
8609
  const html = options.highlighter?.(node.value, lang, {
8073
8610
  ...node.highlightLines && { highlightLines: node.highlightLines },
8074
8611
  ...options.codeLineNumbers !== void 0 && { lineNumbers: options.codeLineNumbers }
@@ -8078,14 +8615,15 @@ function renderCodeBlock(node, options) {
8078
8615
  return `<figure class="tm-code-frame" data-lang="${escapeAttr(lang)}"><figcaption>${escapeHtml$5(node.title)}</figcaption>${pre}</figure>`;
8079
8616
  }
8080
8617
  function renderListItemChildren(children, checked, loose, options) {
8081
- const first = children[0];
8082
- const task = checked === void 0 ? "" : `<input type="checkbox" disabled${checked ? " checked" : ""}> `;
8083
- if (first?.type === "paragraph") {
8084
- const content = `${task}${renderInlines(first.children, options)}`;
8085
- const rest = children.length > 1 ? `\n${children.slice(1).map((child) => renderBlock(child, options)).join("\n")}` : "";
8086
- return `${loose ? `<p>${content}</p>` : content}${rest}`;
8618
+ let result = checked === void 0 ? "" : `<input type="checkbox" disabled${checked ? " checked" : ""}> `;
8619
+ for (let index = 0; index < children.length; index++) {
8620
+ const child = children[index];
8621
+ if (child.type === "paragraph" && (!loose || index === 0)) {
8622
+ result += renderInlines(child.children, options);
8623
+ if (loose) result = `<p>${result}</p>`;
8624
+ } else result += (index ? "\n" : "") + renderBlock(child, options);
8087
8625
  }
8088
- return `${task}${children.map((child) => renderBlock(child, options)).join("\n")}`;
8626
+ return result;
8089
8627
  }
8090
8628
  function renderCallout(node, options) {
8091
8629
  const kind = node.kind.toLowerCase();
@@ -8099,24 +8637,22 @@ function renderFootnotes(items, options) {
8099
8637
  function renderFootnoteItem(item, options) {
8100
8638
  const backref = renderFootnoteBackrefs(item);
8101
8639
  const lastIndex = item.children.length - 1;
8102
- if (lastIndex < 0) return `<p>${backref.trimStart()}</p>`;
8103
- return item.children.map((child, index) => {
8640
+ const result = item.children.map((child, index) => {
8104
8641
  if (index === lastIndex && child.type === "paragraph") return `<p>${renderInlines(child.children, options)}${backref}</p>`;
8105
8642
  return renderBlock(child, options);
8106
- }).join("\n");
8643
+ });
8644
+ if (item.children[lastIndex]?.type !== "paragraph") result.push(`<p>${backref.trimStart()}</p>`);
8645
+ return result.join("\n");
8107
8646
  }
8108
8647
  function renderFootnoteBackrefs(item) {
8109
8648
  let result = "";
8110
8649
  for (let index = 1; index <= (item.referenceCount ?? 1); index++) {
8111
- const referenceId = index === 1 ? item.id : `${item.id}-${index}`;
8650
+ const referenceId = footnoteReferenceId(item.id, index);
8112
8651
  const label = index === 1 ? `${item.number}` : `${item.number}-${index}`;
8113
8652
  result += ` <a data-footnote-backref="" aria-label="Back to reference ${label}" class="data-footnote-backref" href="#user-content-fnref-${escapeAttr(referenceId)}">&#8617;</a>`;
8114
8653
  }
8115
8654
  return result;
8116
8655
  }
8117
- function footnoteReferenceId(node) {
8118
- return node.referenceIndex && node.referenceIndex > 1 ? `${node.id}-${node.referenceIndex}` : node.id;
8119
- }
8120
8656
  function renderComponent(node, options) {
8121
8657
  const tag = node.tagName ?? "md-comment-component";
8122
8658
  return `<${tag}${renderComponentAttrs(node)}>${node.children.map((child) => renderBlock(child, options)).join("\n")}</${tag}>`;
@@ -8146,9 +8682,7 @@ function renderComponentAttrs(node) {
8146
8682
  props["data-component"] = node.name;
8147
8683
  if (!props["data-attributes"]) props["data-attributes"] = JSON.stringify(node.attributes);
8148
8684
  }
8149
- const entries = Object.entries(props);
8150
- if (!entries.length) return "";
8151
- return ` ${entries.map(([key, value]) => `${key}="${escapeAttr(value)}"`).join(" ")}`;
8685
+ return Object.entries(props).map(([key, value]) => ` ${key}="${escapeAttr(value)}"`).join("");
8152
8686
  }
8153
8687
  //#endregion
8154
8688
  //#region ../viewer-kit/src/markdown-autolink.ts
@@ -8326,7 +8860,7 @@ function escapeHtml$4(value) {
8326
8860
  return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&#x27;");
8327
8861
  }
8328
8862
  //#endregion
8329
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/core.js
8863
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/core.js
8330
8864
  function defineLanguage(definition) {
8331
8865
  return definition;
8332
8866
  }
@@ -8370,7 +8904,7 @@ function createHighlighter({ fallbackLanguage = "plaintext", languages }) {
8370
8904
  const innerHtml = renderNodesToHtml(renderTokens(result.tokens, options));
8371
8905
  return {
8372
8906
  ...result,
8373
- html: `<pre class="th-code th-code--${escapeAttribute$1(result.lang)}${options.lineNumbers ? " th-code--line-numbers" : ""}" data-language="${escapeAttribute$1(result.lang)}"><code>${innerHtml}</code></pre>`
8907
+ html: `<pre class="th-code th-code--${escapeHtml$3(result.lang)}${options.lineNumbers ? " th-code--line-numbers" : ""}" data-language="${escapeHtml$3(result.lang)}"><code>${innerHtml}</code></pre>`
8374
8908
  };
8375
8909
  }
8376
8910
  function renderCodeBlockData({ code, decorations, lang, lineNumbers, title }) {
@@ -8402,11 +8936,17 @@ function createHighlighter({ fallbackLanguage = "plaintext", languages }) {
8402
8936
  };
8403
8937
  }
8404
8938
  function renderTokens(tokens, options = {}) {
8939
+ const rangeDecorations = [];
8940
+ const lineDecorations = [];
8941
+ for (const decoration of options.decorations || []) if (decoration.range) rangeDecorations.push(decoration);
8942
+ else lineDecorations.push(decoration);
8943
+ const wrapLines = Boolean(options.lineNumbers || lineDecorations.length);
8944
+ const cursor = {
8945
+ index: 0,
8946
+ offset: 0
8947
+ };
8948
+ if (!wrapLines) return renderTokenSlice(tokens, 0, Infinity, rangeDecorations, cursor);
8405
8949
  const code = tokens.map((token) => token.value).join("");
8406
- const decorations = options.decorations || [];
8407
- const rangeDecorations = decorations.filter(isRangeDecoration);
8408
- const lineDecorations = decorations.filter(isLineDecoration);
8409
- if (!Boolean(options.lineNumbers || lineDecorations.length)) return renderTokenSlice(tokens, 0, code.length, rangeDecorations);
8410
8950
  const nodes = [];
8411
8951
  const lineStarts = getLineStarts(code);
8412
8952
  for (let index = 0; index < lineStarts.length; index++) {
@@ -8423,7 +8963,7 @@ function renderTokens(tokens, options = {}) {
8423
8963
  ...mergeData(active),
8424
8964
  line: String(line)
8425
8965
  },
8426
- children: renderTokenSlice(tokens, start, end, rangeDecorations)
8966
+ children: renderTokenSlice(tokens, start, end, rangeDecorations, cursor)
8427
8967
  });
8428
8968
  if (hasNewline) nodes.push({
8429
8969
  type: "text",
@@ -8439,31 +8979,52 @@ function renderNodesToHtml(nodes) {
8439
8979
  html += escapeHtml$3(node.value);
8440
8980
  continue;
8441
8981
  }
8442
- const className = node.classNames.map(escapeAttribute$1).join(" ");
8443
- const data = Object.entries(node.data || {}).map(([key, value]) => ` data-${escapeAttribute$1(toKebabCase(key))}="${escapeAttribute$1(value)}"`).join("");
8982
+ const className = escapeHtml$3(node.classNames.join(" "));
8983
+ let data = "";
8984
+ if (node.data) for (const [key, value] of Object.entries(node.data)) data += ` data-${normalizeDataKey(key)}="${escapeHtml$3(value)}"`;
8444
8985
  html += `<span${className ? ` class="${className}"` : ""}${data}>${renderNodesToHtml(node.children)}</span>`;
8445
8986
  }
8446
8987
  return html;
8447
8988
  }
8989
+ const htmlEscapes = {
8990
+ "&": "&amp;",
8991
+ "<": "&lt;",
8992
+ ">": "&gt;",
8993
+ "\"": "&quot;",
8994
+ "'": "&#39;"
8995
+ };
8448
8996
  function escapeHtml$3(value) {
8449
- return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&#39;");
8997
+ return value.replace(/[&<>"']/g, (character) => htmlEscapes[character]);
8450
8998
  }
8451
8999
  function normalizeName(value) {
8452
9000
  return value.trim().toLowerCase();
8453
9001
  }
8454
9002
  function normalizeTokenRanges(codeLength, input) {
8455
9003
  const ranges = [];
8456
- const candidates = input.map((candidate) => ({
8457
- ...candidate,
8458
- start: Math.max(0, Math.min(codeLength, candidate.start)),
8459
- end: Math.max(0, Math.min(codeLength, candidate.end))
8460
- })).sort((a, b) => a.start - b.start);
9004
+ let sorted = true;
9005
+ let previousStart = 0;
9006
+ for (const candidate of input) {
9007
+ if (!Number.isInteger(candidate.start) || !Number.isInteger(candidate.end)) continue;
9008
+ const start = Math.max(0, Math.min(codeLength, candidate.start));
9009
+ const end = Math.max(0, Math.min(codeLength, candidate.end));
9010
+ if (start >= end) continue;
9011
+ if (start < previousStart) sorted = false;
9012
+ previousStart = start;
9013
+ ranges.push({
9014
+ className: candidate.className,
9015
+ start,
9016
+ end
9017
+ });
9018
+ }
9019
+ if (!sorted) ranges.sort((a, b) => a.start - b.start);
8461
9020
  let end = 0;
8462
- for (const candidate of candidates) {
8463
- if (candidate.start >= candidate.end || candidate.start < end) continue;
8464
- ranges.push(candidate);
9021
+ let count = 0;
9022
+ for (const candidate of ranges) {
9023
+ if (candidate.start < end) continue;
9024
+ ranges[count++] = candidate;
8465
9025
  end = candidate.end;
8466
9026
  }
9027
+ ranges.length = count;
8467
9028
  return ranges;
8468
9029
  }
8469
9030
  function rangesToTokens(code, ranges) {
@@ -8480,22 +9041,26 @@ function rangesToTokens(code, ranges) {
8480
9041
  if (index < code.length) tokens.push({ value: code.slice(index) });
8481
9042
  return tokens;
8482
9043
  }
8483
- function renderTokenSlice(tokens, start, end, decorations) {
9044
+ function renderTokenSlice(tokens, start, end, decorations, cursor) {
8484
9045
  const nodes = [];
8485
- let tokenStart = 0;
8486
- for (const token of tokens) {
9046
+ for (; cursor.index < tokens.length; cursor.index++) {
9047
+ const token = tokens[cursor.index];
9048
+ const tokenStart = cursor.offset;
8487
9049
  const tokenEnd = tokenStart + token.value.length;
8488
9050
  const sliceStart = Math.max(start, tokenStart);
8489
9051
  const sliceEnd = Math.min(end, tokenEnd);
8490
9052
  if (sliceStart < sliceEnd) {
8491
- const boundaries = /* @__PURE__ */ new Set([sliceStart, sliceEnd]);
8492
- for (const decoration of decorations) {
8493
- const [decorationStart, decorationEnd] = decoration.range;
8494
- if (decorationEnd <= sliceStart || decorationStart >= sliceEnd) continue;
8495
- boundaries.add(Math.max(sliceStart, decorationStart));
8496
- boundaries.add(Math.min(sliceEnd, decorationEnd));
9053
+ let sorted = [sliceStart, sliceEnd];
9054
+ if (decorations.length) {
9055
+ const boundaries = new Set(sorted);
9056
+ for (const decoration of decorations) {
9057
+ const [decorationStart, decorationEnd] = decoration.range;
9058
+ if (decorationEnd <= sliceStart || decorationStart >= sliceEnd) continue;
9059
+ boundaries.add(Math.max(sliceStart, decorationStart));
9060
+ boundaries.add(Math.min(sliceEnd, decorationEnd));
9061
+ }
9062
+ sorted = [...boundaries].sort((a, b) => a - b);
8497
9063
  }
8498
- const sorted = [...boundaries].sort((a, b) => a - b);
8499
9064
  for (let index = 0; index < sorted.length - 1; index++) {
8500
9065
  const segmentStart = sorted[index];
8501
9066
  const segmentEnd = sorted[index + 1];
@@ -8508,27 +9073,23 @@ function renderTokenSlice(tokens, start, end, decorations) {
8508
9073
  classNames: ["th-token", `th-${token.className}`],
8509
9074
  children: [node]
8510
9075
  };
8511
- const active = decorations.filter((decoration) => decoration.range[0] <= segmentStart && decoration.range[1] >= segmentEnd);
8512
- for (const decoration of active) node = {
8513
- type: "element",
8514
- classNames: ["th-decoration", ...splitClassNames(decoration.className)],
8515
- data: stringifyData(decoration.data),
8516
- children: [node]
8517
- };
9076
+ for (const decoration of decorations) {
9077
+ if (decoration.range[0] > segmentStart || decoration.range[1] < segmentEnd) continue;
9078
+ node = {
9079
+ type: "element",
9080
+ classNames: ["th-decoration", ...splitClassNames(decoration.className)],
9081
+ data: stringifyData(decoration.data),
9082
+ children: [node]
9083
+ };
9084
+ }
8518
9085
  nodes.push(node);
8519
9086
  }
8520
9087
  }
8521
- tokenStart = tokenEnd;
8522
- if (tokenStart >= end) break;
9088
+ if (tokenEnd > end) break;
9089
+ cursor.offset = tokenEnd;
8523
9090
  }
8524
9091
  return nodes;
8525
9092
  }
8526
- function isRangeDecoration(decoration) {
8527
- return "range" in decoration;
8528
- }
8529
- function isLineDecoration(decoration) {
8530
- return "lines" in decoration;
8531
- }
8532
9093
  function getLineStarts(code) {
8533
9094
  const starts = [0];
8534
9095
  for (let index = 0; index < code.length; index++) if (code[index] === "\n" && index + 1 < code.length) starts.push(index + 1);
@@ -8555,17 +9116,13 @@ function splitClassNames(className) {
8555
9116
  function toKebabCase(value) {
8556
9117
  return value.replace(/[A-Z]/g, (character) => `-${character.toLowerCase()}`);
8557
9118
  }
8558
- function escapeAttribute$1(value) {
8559
- return escapeHtml$3(value);
8560
- }
8561
9119
  //#endregion
8562
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/internal/patterns.js
9120
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/internal/patterns.js
8563
9121
  function patternTokenizer(patterns) {
8564
9122
  return (code) => collectPatternRanges(code, patterns);
8565
9123
  }
8566
- function collectPatternRanges(code, patterns, initial = []) {
9124
+ function collectPatternRanges(code, patterns, initial = [], occupied = new Uint8Array(code.length)) {
8567
9125
  const ranges = [...initial];
8568
- const occupied = new Uint8Array(code.length);
8569
9126
  for (const range of initial) occupied.fill(1, range.start, range.end);
8570
9127
  for (const pattern of patterns) {
8571
9128
  if ("collect" in pattern) {
@@ -8580,7 +9137,7 @@ function collectPatternRanges(code, patterns, initial = []) {
8580
9137
  if (!match[0].length) regex.lastIndex++;
8581
9138
  continue;
8582
9139
  }
8583
- const offset = pattern.group ? match[0].indexOf(value) : 0;
9140
+ const offset = pattern.group ? match[0].length - value.length : 0;
8584
9141
  const start = match.index + offset;
8585
9142
  addRange(ranges, occupied, {
8586
9143
  start,
@@ -8605,14 +9162,14 @@ function addRange(ranges, occupied, range) {
8605
9162
  return true;
8606
9163
  }
8607
9164
  function cloneRegex(regex) {
8608
- return new RegExp(regex.source, regex.flags.includes("g") ? regex.flags : `${regex.flags}g`);
9165
+ return new RegExp(regex.source, regex.global ? regex.flags : `${regex.flags}g`);
8609
9166
  }
8610
9167
  function hasOverlap(occupied, start, end) {
8611
9168
  for (let index = start; index < end; index++) if (occupied[index]) return true;
8612
9169
  return false;
8613
9170
  }
8614
9171
  //#endregion
8615
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/css.js
9172
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/css.js
8616
9173
  const css = defineLanguage({
8617
9174
  name: "css",
8618
9175
  tokenize: patternTokenizer([
@@ -8645,7 +9202,7 @@ const css = defineLanguage({
8645
9202
  ])
8646
9203
  });
8647
9204
  //#endregion
8648
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/diff.js
9205
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/diff.js
8649
9206
  const diff = defineLanguage({
8650
9207
  name: "diff",
8651
9208
  aliases: ["patch"],
@@ -8665,7 +9222,7 @@ const diff = defineLanguage({
8665
9222
  ])
8666
9223
  });
8667
9224
  //#endregion
8668
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/dockerfile.js
9225
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/dockerfile.js
8669
9226
  const dockerfile = defineLanguage({
8670
9227
  name: "dockerfile",
8671
9228
  aliases: ["docker"],
@@ -8693,12 +9250,16 @@ const dockerfile = defineLanguage({
8693
9250
  ])
8694
9251
  });
8695
9252
  //#endregion
8696
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/internal/markup.js
9253
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/internal/markup.js
9254
+ const rawTextClosing = {
9255
+ script: /<\/script(?=[\s/>])/gi,
9256
+ style: /<\/style(?=[\s/>])/gi
9257
+ };
8697
9258
  function collectMarkupRanges(code, context, mode = "html") {
8698
9259
  const ranges = [];
8699
9260
  const regions = [];
8700
9261
  let index = 0;
8701
- while (index < code.length) {
9262
+ while ((index = code.indexOf("<", index)) >= 0) {
8702
9263
  if (code.startsWith("<!--", index)) {
8703
9264
  const close = code.indexOf("-->", index + 4);
8704
9265
  const end = close < 0 ? code.length : close + 3;
@@ -8721,10 +9282,6 @@ function collectMarkupRanges(code, context, mode = "html") {
8721
9282
  index = close < 0 ? code.length : close + 2;
8722
9283
  continue;
8723
9284
  }
8724
- if (code[index] !== "<") {
8725
- index++;
8726
- continue;
8727
- }
8728
9285
  const closing = code[index + 1] === "/";
8729
9286
  const nameStart = index + (closing ? 2 : 1);
8730
9287
  const nameMatch = /^[A-Za-z][\w:.-]*/.exec(code.slice(nameStart));
@@ -8745,16 +9302,17 @@ function collectMarkupRanges(code, context, mode = "html") {
8745
9302
  });
8746
9303
  if (!closing) collectAttributes(code, nameStart + nameMatch[0].length, tagEnd, ranges);
8747
9304
  if (!closing && (tagName === "script" || tagName === "style")) {
8748
- const closingTag = `</${tagName}`;
8749
- const contentEnd = code.toLowerCase().indexOf(closingTag, tagEnd + 1);
8750
- if (contentEnd >= 0) {
8751
- const lang = getEmbeddedLanguage(tagName, code.slice(index, tagEnd + 1));
8752
- regions.push({
8753
- start: tagEnd + 1,
8754
- end: contentEnd,
8755
- lang
8756
- });
8757
- }
9305
+ const rawTextClose = rawTextClosing[tagName];
9306
+ rawTextClose.lastIndex = tagEnd + 1;
9307
+ const contentEnd = rawTextClose.exec(code)?.index ?? code.length;
9308
+ const lang = getEmbeddedLanguage(tagName, code.slice(index, tagEnd + 1));
9309
+ regions.push({
9310
+ start: tagEnd + 1,
9311
+ end: contentEnd,
9312
+ lang
9313
+ });
9314
+ index = contentEnd;
9315
+ continue;
8758
9316
  }
8759
9317
  index = tagEnd + 1;
8760
9318
  }
@@ -8845,7 +9403,7 @@ function findQuoteEnd(code, start, quote, limit) {
8845
9403
  return limit;
8846
9404
  }
8847
9405
  //#endregion
8848
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/html.js
9406
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/html.js
8849
9407
  const html = defineLanguage({
8850
9408
  name: "html",
8851
9409
  aliases: [
@@ -8856,7 +9414,7 @@ const html = defineLanguage({
8856
9414
  tokenize: (code, context) => collectMarkupRanges(code, context)
8857
9415
  });
8858
9416
  //#endregion
8859
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/internal/script.js
9417
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/internal/script.js
8860
9418
  const semanticPatterns = [
8861
9419
  {
8862
9420
  className: "function",
@@ -8881,7 +9439,7 @@ const semanticPatterns = [
8881
9439
  },
8882
9440
  {
8883
9441
  className: "function",
8884
- regex: /(^|[^.A-Za-z0-9_$])([A-Za-z_$][\w$]*)\s*(?=\()/g,
9442
+ regex: /(^|[^.A-Za-z0-9_$])([A-Za-z_$][\w$]*)(?=\s*\()/g,
8885
9443
  group: 2
8886
9444
  },
8887
9445
  {
@@ -8898,8 +9456,7 @@ function collectScriptRanges(code, jsx = false, jsxAtLineStart = false) {
8898
9456
  const jsxText = jsx ? new Uint8Array(code.length) : void 0;
8899
9457
  const initial = [];
8900
9458
  collectScriptInitialRanges(code, jsx, jsxAtLineStart, jsxText, initial);
8901
- const ranges = collectPatternRanges(code, semanticPatterns, initial);
8902
- return jsxText ? ranges.filter((range) => !jsxText[range.start]) : ranges;
9459
+ return collectPatternRanges(code, semanticPatterns, initial, jsxText);
8903
9460
  }
8904
9461
  function collectScriptInitialRanges(code, jsx, jsxAtLineStart, jsxText, ranges, index = 0, limit = code.length, tagBody = false) {
8905
9462
  const expressions = [];
@@ -9096,6 +9653,10 @@ function findInterpolationEnd(code, start) {
9096
9653
  index = close < 0 ? code.length : close + 2;
9097
9654
  continue;
9098
9655
  }
9656
+ if (character === "/" && isRegexStart(code, index)) {
9657
+ index = findRegexEnd(code, index);
9658
+ continue;
9659
+ }
9099
9660
  if (character === "{") depth++;
9100
9661
  if (character === "}" && --depth === 0) return index;
9101
9662
  index++;
@@ -9174,7 +9735,7 @@ function findLineEnd(code, start) {
9174
9735
  return end < 0 ? code.length : end;
9175
9736
  }
9176
9737
  //#endregion
9177
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/js.js
9738
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/js.js
9178
9739
  const js = defineLanguage({
9179
9740
  name: "js",
9180
9741
  aliases: [
@@ -9186,7 +9747,7 @@ const js = defineLanguage({
9186
9747
  tokenize: (code) => collectScriptRanges(code)
9187
9748
  });
9188
9749
  //#endregion
9189
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/json.js
9750
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/json.js
9190
9751
  const json = defineLanguage({
9191
9752
  name: "json",
9192
9753
  aliases: ["jsonc", "json5"],
@@ -9206,13 +9767,13 @@ const json = defineLanguage({
9206
9767
  ])
9207
9768
  });
9208
9769
  //#endregion
9209
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/jsx.js
9770
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/jsx.js
9210
9771
  const jsx = defineLanguage({
9211
9772
  name: "jsx",
9212
9773
  tokenize: (code) => collectScriptRanges(code, true)
9213
9774
  });
9214
9775
  //#endregion
9215
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/markdown.js
9776
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/markdown.js
9216
9777
  const markdown = defineLanguage({
9217
9778
  name: "markdown",
9218
9779
  aliases: ["md"],
@@ -9273,7 +9834,7 @@ function collectFencedCode(code, context) {
9273
9834
  function fillCodeRange(start, end, embedded) {
9274
9835
  const ranges = [];
9275
9836
  let index = start;
9276
- for (const range of [...embedded].sort((a, b) => a.start - b.start)) {
9837
+ for (const range of embedded) {
9277
9838
  if (range.start > index) ranges.push({
9278
9839
  start: index,
9279
9840
  end: range.start,
@@ -9290,46 +9851,44 @@ function fillCodeRange(start, end, embedded) {
9290
9851
  return ranges;
9291
9852
  }
9292
9853
  //#endregion
9293
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/python.js
9854
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/python.js
9294
9855
  const python = defineLanguage({
9295
9856
  name: "python",
9296
9857
  aliases: ["py"],
9297
- tokenize(code) {
9298
- return collectPatternRanges(code, [
9299
- {
9300
- className: (match) => match[0].startsWith("#") ? "comment" : "string",
9301
- regex: /#[^\n]*|(?:br|rb|fr|rf|[rubf])?(?:"""[\s\S]*?"""|'''[\s\S]*?'''|"(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*')/gi
9302
- },
9303
- {
9304
- className: "keyword",
9305
- regex: /\b(?:and|as|assert|async|await|break|case|class|continue|def|del|elif|else|except|finally|for|from|global|if|import|in|is|lambda|match|nonlocal|not|or|pass|raise|return|try|while|with|yield)\b/g
9306
- },
9307
- {
9308
- className: "literal",
9309
- regex: /\b(?:False|None|True|NotImplemented|Ellipsis)\b/g
9310
- },
9311
- {
9312
- className: "function",
9313
- regex: /@[A-Za-z_][\w.]*/g
9314
- },
9315
- {
9316
- className: "function",
9317
- regex: /\bdef\s+([A-Za-z_]\w*)/g,
9318
- group: 1
9319
- },
9320
- {
9321
- className: "type",
9322
- regex: /\b(?:bool|bytes|dict|float|frozenset|int|list|object|set|str|tuple|type)\b/g
9323
- },
9324
- {
9325
- className: "number",
9326
- regex: /\b(?:0x[\da-f_]+|0b[01_]+|0o[0-7_]+|\d[\d_]*(?:\.\d[\d_]*)?(?:e[+-]?\d[\d_]*)?j?)\b/gi
9327
- }
9328
- ]);
9329
- }
9858
+ tokenize: patternTokenizer([
9859
+ {
9860
+ className: (match) => match[0].startsWith("#") ? "comment" : "string",
9861
+ regex: /#[^\n]*|(?:br|rb|fr|rf|[rubf])?(?:"""[\s\S]*?"""|'''[\s\S]*?'''|"(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*')/gi
9862
+ },
9863
+ {
9864
+ className: "keyword",
9865
+ regex: /\b(?:and|as|assert|async|await|break|case|class|continue|def|del|elif|else|except|finally|for|from|global|if|import|in|is|lambda|match|nonlocal|not|or|pass|raise|return|try|while|with|yield)\b/g
9866
+ },
9867
+ {
9868
+ className: "literal",
9869
+ regex: /\b(?:False|None|True|NotImplemented|Ellipsis)\b/g
9870
+ },
9871
+ {
9872
+ className: "function",
9873
+ regex: /@[A-Za-z_][\w.]*/g
9874
+ },
9875
+ {
9876
+ className: "function",
9877
+ regex: /\bdef\s+([A-Za-z_]\w*)/g,
9878
+ group: 1
9879
+ },
9880
+ {
9881
+ className: "type",
9882
+ regex: /\b(?:bool|bytes|dict|float|frozenset|int|list|object|set|str|tuple|type)\b/g
9883
+ },
9884
+ {
9885
+ className: "number",
9886
+ regex: /\b(?:0x[\da-f_]+|0b[01_]+|0o[0-7_]+|\d[\d_]*(?:\.\d[\d_]*)?(?:e[+-]?\d[\d_]*)?j?)\b/gi
9887
+ }
9888
+ ])
9330
9889
  });
9331
9890
  //#endregion
9332
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/shell.js
9891
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/shell.js
9333
9892
  const shell = defineLanguage({
9334
9893
  name: "shell",
9335
9894
  aliases: [
@@ -9339,32 +9898,34 @@ const shell = defineLanguage({
9339
9898
  "cmd",
9340
9899
  "console"
9341
9900
  ],
9342
- tokenize(code) {
9343
- return collectPatternRanges(code, [
9344
- { collect: collectShellLexicalRanges },
9345
- {
9346
- className: "variable",
9347
- regex: /\$[A-Za-z_][A-Za-z0-9_]*|\b[A-Z_][A-Z0-9_]*(?==)/g
9348
- },
9349
- {
9350
- className: "keyword",
9351
- regex: /\b(?:case|do|done|elif|else|esac|export|fi|for|function|if|in|select|then|time|until|while)\b/g
9352
- },
9353
- {
9354
- className: "command",
9355
- regex: /(^|[\n;|&])\s*([A-Za-z0-9_./-]+)(?=\s|$)/g,
9356
- group: 2
9357
- }
9358
- ]);
9359
- }
9901
+ tokenize: patternTokenizer([
9902
+ { collect: collectShellLexicalRanges },
9903
+ {
9904
+ className: "variable",
9905
+ regex: /\$[A-Za-z_][A-Za-z0-9_]*|\b[A-Z_][A-Z0-9_]*(?==)/g
9906
+ },
9907
+ {
9908
+ className: "keyword",
9909
+ regex: /\b(?:case|do|done|elif|else|esac|export|fi|for|function|if|in|select|then|time|until|while)\b/g
9910
+ },
9911
+ {
9912
+ className: "command",
9913
+ regex: /(^|[\n;|&])\s*([A-Za-z0-9_./-]+)(?=\s|$)/g,
9914
+ group: 2
9915
+ }
9916
+ ])
9360
9917
  });
9361
9918
  function collectShellLexicalRanges(code) {
9362
- const ranges = [];
9363
- collectHeredocs(code, ranges);
9919
+ const heredocs = [];
9920
+ collectHeredocs(code, heredocs);
9921
+ const ranges = [...heredocs];
9922
+ let heredocIndex = 0;
9364
9923
  let index = 0;
9365
9924
  while (index < code.length) {
9366
- if (insideRange(index, ranges)) {
9367
- index = ranges.find((range) => range.start <= index && range.end > index).end;
9925
+ while (heredocIndex < heredocs.length && heredocs[heredocIndex].end <= index) heredocIndex++;
9926
+ const heredoc = heredocs[heredocIndex];
9927
+ if (heredoc && heredoc.start <= index) {
9928
+ index = heredoc.end;
9368
9929
  continue;
9369
9930
  }
9370
9931
  const character = code[index];
@@ -9376,6 +9937,7 @@ function collectShellLexicalRanges(code) {
9376
9937
  end++;
9377
9938
  break;
9378
9939
  } else end++;
9940
+ end = Math.min(end, code.length);
9379
9941
  ranges.push({
9380
9942
  start: index,
9381
9943
  end,
@@ -9418,7 +9980,7 @@ function collectHeredocs(code, ranges) {
9418
9980
  const bodyStartLine = code.indexOf("\n", match.index + match[0].length);
9419
9981
  if (bodyStartLine < 0) continue;
9420
9982
  const bodyStart = bodyStartLine + 1;
9421
- const closingMatch = new RegExp(`^\\t*${escapeRegex(match[2])}\\s*$`, "m").exec(code.slice(bodyStart));
9983
+ const closingMatch = new RegExp(`^\\t*${match[2]}\\s*$`, "m").exec(code.slice(bodyStart));
9422
9984
  if (!closingMatch) {
9423
9985
  ranges.push({
9424
9986
  start: bodyStart,
@@ -9449,14 +10011,8 @@ function isInsideQuote(code, index) {
9449
10011
  else if (!quote && (code[cursor] === "\"" || code[cursor] === "'")) quote = code[cursor];
9450
10012
  return Boolean(quote);
9451
10013
  }
9452
- function insideRange(index, ranges) {
9453
- return ranges.some((range) => range.start <= index && range.end > index);
9454
- }
9455
- function escapeRegex(value) {
9456
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
9457
- }
9458
10014
  //#endregion
9459
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/sql.js
10015
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/sql.js
9460
10016
  const sql = defineLanguage({
9461
10017
  name: "sql",
9462
10018
  tokenize: patternTokenizer([
@@ -9483,7 +10039,7 @@ const sql = defineLanguage({
9483
10039
  ])
9484
10040
  });
9485
10041
  //#endregion
9486
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/toml.js
10042
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/toml.js
9487
10043
  const toml = defineLanguage({
9488
10044
  name: "toml",
9489
10045
  tokenize: patternTokenizer([
@@ -9511,20 +10067,20 @@ const toml = defineLanguage({
9511
10067
  ])
9512
10068
  });
9513
10069
  //#endregion
9514
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/ts.js
10070
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/ts.js
9515
10071
  const ts = defineLanguage({
9516
10072
  name: "ts",
9517
10073
  aliases: ["typescript", "angular-ts"],
9518
10074
  tokenize: (code) => collectScriptRanges(code)
9519
10075
  });
9520
10076
  //#endregion
9521
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/tsx.js
10077
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/tsx.js
9522
10078
  const tsx = defineLanguage({
9523
10079
  name: "tsx",
9524
10080
  tokenize: (code) => collectScriptRanges(code, true)
9525
10081
  });
9526
10082
  //#endregion
9527
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/yaml.js
10083
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/yaml.js
9528
10084
  const yaml = defineLanguage({
9529
10085
  name: "yaml",
9530
10086
  aliases: ["yml"],
@@ -9630,7 +10186,7 @@ function collectYamlValues(code) {
9630
10186
  return ranges;
9631
10187
  }
9632
10188
  //#endregion
9633
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/theme.js
10189
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/theme.js
9634
10190
  const themeTokenClasses = [
9635
10191
  "token",
9636
10192
  "attr",
@@ -9684,27 +10240,7 @@ function createThemeBaseCss(options = {}) {
9684
10240
  color: var(--th-token);
9685
10241
  }
9686
10242
 
9687
- .th-token { color: var(--th-token); }
9688
- .th-keyword { color: var(--th-keyword); }
9689
- .th-string { color: var(--th-string); }
9690
- .th-comment { color: var(--th-comment); }
9691
- .th-function { color: var(--th-function); }
9692
- .th-type { color: var(--th-type); }
9693
- .th-property { color: var(--th-property); }
9694
- .th-tag { color: var(--th-tag); }
9695
- .th-attr { color: var(--th-attr); }
9696
- .th-literal { color: var(--th-literal); }
9697
- .th-number { color: var(--th-number); }
9698
- .th-variable { color: var(--th-variable); }
9699
- .th-operator { color: var(--th-operator); }
9700
- .th-inserted { color: var(--th-inserted); }
9701
- .th-deleted { color: var(--th-deleted); }
9702
- .th-meta { color: var(--th-meta); }
9703
- .th-heading { color: var(--th-heading); }
9704
- .th-link { color: var(--th-link); }
9705
- .th-code-inline { color: var(--th-code-inline); }
9706
- .th-selector { color: var(--th-selector); }
9707
- .th-command { color: var(--th-command); }
10243
+ ${themeTokenClasses.map((token) => `.th-${token} { color: var(--th-${token}); }`).join("\n")}
9708
10244
  .th-line { display: inline-block; min-width: 100%; width: max-content; }
9709
10245
  ${lineNumbersSelector} code { counter-reset: th-line; }
9710
10246
  ${lineNumbersSelector} .th-line::before {
@@ -9718,7 +10254,7 @@ ${lineNumbersSelector} .th-line::before {
9718
10254
  }`;
9719
10255
  }
9720
10256
  //#endregion
9721
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/themes/github-dark.js
10257
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/themes/github-dark.js
9722
10258
  const githubDarkTheme = {
9723
10259
  background: "#0d1117",
9724
10260
  foreground: "#c9d1d9",
@@ -10581,6 +11117,8 @@ function renderPreviewShell(options) {
10581
11117
  const payload = readyPayload();
10582
11118
  postToFrame(payload);
10583
11119
  postToFrame({ kind: 'annotate-mode', enabled: annotateMode });
11120
+ // The CLI preview has no external-link interstitial; open links directly.
11121
+ postToFrame({ kind: 'external-link-policy', mode: 'direct' });
10584
11122
  readyBurstTimer = setInterval(() => {
10585
11123
  sent += 1;
10586
11124
  if (sent >= CONFIG.readyRepeat) {
@@ -10590,6 +11128,7 @@ function renderPreviewShell(options) {
10590
11128
  }
10591
11129
  postToFrame(payload);
10592
11130
  postToFrame({ kind: 'annotate-mode', enabled: annotateMode });
11131
+ postToFrame({ kind: 'external-link-policy', mode: 'direct' });
10593
11132
  }, CONFIG.readyIntervalMs);
10594
11133
  }
10595
11134
 
@@ -12099,12 +12638,14 @@ async function runCommentsList(parsed, mode) {
12099
12638
  return comments.error ? { error: comments.error } : { data: comments.body };
12100
12639
  });
12101
12640
  if (result.error) return writeFailure(command, result.error, mode, 1);
12102
- const comments = Array.isArray(result.data?.comments) ? result.data.comments : [];
12641
+ const contracted = COMMENTS_LIST_RESPONSE_SCHEMA.safeParse(result.data);
12642
+ const raw = isRecord$1(result.data) ? result.data : null;
12643
+ const comments = contracted.success ? contracted.data.comments : Array.isArray(raw?.comments) ? raw.comments : [];
12103
12644
  writeSuccess(command, {
12104
12645
  artifact_id: artifactId,
12105
- share_url: configString(result.data?.share_url),
12646
+ share_url: configString(contracted.success ? contracted.data.share_url : raw?.share_url),
12106
12647
  comments,
12107
- has_more: result.data?.has_more === true
12648
+ has_more: (contracted.success ? contracted.data.has_more : raw?.has_more) === true
12108
12649
  }, mode);
12109
12650
  if (!mode.json && comments.length === 0) writeText("No comments yet.\n");
12110
12651
  }
@@ -12142,14 +12683,16 @@ async function runCommentsPost(parsed, mode) {
12142
12683
  return posted.error ? { error: posted.error } : { data: posted.body };
12143
12684
  });
12144
12685
  if (result.error) return writeFailure(command, result.error, mode, 1);
12145
- const threadId = configString(result.data?.thread_id);
12686
+ const postedResponse = isContract(COMMENT_POST_RESPONSE_SCHEMA, result.data) ? result.data : null;
12687
+ const postedRaw = isRecord$1(result.data) ? result.data : null;
12688
+ const threadId = configString(postedResponse?.thread_id ?? postedRaw?.thread_id);
12146
12689
  if (!threadId) return writeFailure(command, serviceError("Comment was saved but the response had no thread id."), mode, 1);
12147
12690
  writeSuccess(command, {
12148
12691
  artifact_id: artifactId,
12149
- share_url: configString(result.data?.share_url),
12692
+ share_url: configString(postedResponse?.share_url ?? postedRaw?.share_url),
12150
12693
  thread_id: threadId,
12151
- reply: result.data?.reply === true,
12152
- thread: result.data?.thread ?? null
12694
+ reply: (postedResponse?.reply ?? postedRaw?.reply) === true,
12695
+ thread: postedResponse?.thread ?? postedRaw?.thread ?? null
12153
12696
  }, mode);
12154
12697
  }
12155
12698
  async function runCommentsEdit(parsed, mode) {
@@ -12166,13 +12709,16 @@ async function runCommentsEdit(parsed, mode) {
12166
12709
  body: body.value
12167
12710
  }, mode);
12168
12711
  if (!result) return;
12169
- const threadId = configString(result.thread_id);
12170
- if (!threadId || result.thread === void 0) return writeFailure(command, serviceError("Comment was changed but the response had no thread."), mode, 1);
12712
+ const actionResponse = isContract(COMMENT_ACTION_RESPONSE_SCHEMA, result) ? result : null;
12713
+ const actionRaw = isRecord$1(result) ? result : null;
12714
+ const threadId = configString(actionResponse?.thread_id ?? actionRaw?.thread_id);
12715
+ const thread = actionResponse?.thread ?? actionRaw?.thread;
12716
+ if (!threadId || thread === void 0) return writeFailure(command, serviceError("Comment was changed but the response had no thread."), mode, 1);
12171
12717
  writeSuccess(command, {
12172
12718
  artifact_id: target.artifactId,
12173
- share_url: configString(result.share_url),
12719
+ share_url: configString(actionResponse?.share_url ?? actionRaw?.share_url),
12174
12720
  thread_id: threadId,
12175
- thread: result.thread
12721
+ thread
12176
12722
  }, mode);
12177
12723
  }
12178
12724
  async function runCommentsResolve(parsed, mode) {
@@ -12187,25 +12733,30 @@ async function runCommentsDelete(parsed, mode) {
12187
12733
  if (target.error) return writeFailure(command, target.error, mode, 1);
12188
12734
  const threadId = requiredOption(parsed.options.threadId, "--thread-id is required.", "Run comments list and retry with a listed thread_id.");
12189
12735
  if (threadId.error) return writeFailure(command, threadId.error, mode, 1);
12190
- const payload = {
12736
+ let payload = {
12191
12737
  action: "delete",
12192
12738
  thread_id: threadId.value
12193
12739
  };
12194
12740
  if (parsed.options.messageId !== void 0) {
12195
12741
  if (!parsed.options.messageId.trim()) return writeFailure(command, validationError("--message-id cannot be empty.", "Run comments list and retry with a listed message_id."), mode, 1);
12196
- payload.message_id = parsed.options.messageId.trim();
12742
+ payload = {
12743
+ ...payload,
12744
+ message_id: parsed.options.messageId.trim()
12745
+ };
12197
12746
  }
12198
12747
  const result = await postCommentAction(parsed, command, target.artifactId, payload, mode);
12199
12748
  if (!result) return;
12200
- const responseThreadId = configString(result.thread_id);
12201
- if (!responseThreadId || result.deleted !== true) return writeFailure(command, serviceError("Comment was deleted but the response was incomplete."), mode, 1);
12749
+ const deleteResponse = isContract(COMMENT_DELETE_RESPONSE_SCHEMA, result) ? result : null;
12750
+ const deleteRaw = isRecord$1(result) ? result : null;
12751
+ const responseThreadId = configString(deleteResponse?.thread_id ?? deleteRaw?.thread_id);
12752
+ if (!responseThreadId || (deleteResponse?.deleted ?? deleteRaw?.deleted) !== true) return writeFailure(command, serviceError("Comment was deleted but the response was incomplete."), mode, 1);
12202
12753
  writeSuccess(command, {
12203
12754
  artifact_id: target.artifactId,
12204
- share_url: configString(result.share_url),
12755
+ share_url: configString(deleteResponse?.share_url ?? deleteRaw?.share_url),
12205
12756
  thread_id: responseThreadId,
12206
12757
  deleted: true,
12207
- thread_deleted: result.thread_deleted === true,
12208
- ...result.thread !== void 0 ? { thread: result.thread } : {}
12758
+ thread_deleted: (deleteResponse?.thread_deleted ?? deleteRaw?.thread_deleted) === true,
12759
+ ...(deleteResponse?.thread ?? deleteRaw?.thread) !== void 0 ? { thread: deleteResponse?.thread ?? deleteRaw?.thread } : {}
12209
12760
  }, mode);
12210
12761
  }
12211
12762
  async function runCommentsStatus(parsed, mode, command, action) {
@@ -12213,18 +12764,24 @@ async function runCommentsStatus(parsed, mode, command, action) {
12213
12764
  if (target.error) return writeFailure(command, target.error, mode, 1);
12214
12765
  const threadId = requiredOption(parsed.options.threadId, "--thread-id is required.", "Run comments list and retry with a listed thread_id.");
12215
12766
  if (threadId.error) return writeFailure(command, threadId.error, mode, 1);
12216
- const result = await postCommentAction(parsed, command, target.artifactId, {
12767
+ const result = await postCommentAction(parsed, command, target.artifactId, action === "resolve" ? {
12768
+ action,
12769
+ thread_id: threadId.value
12770
+ } : {
12217
12771
  action,
12218
12772
  thread_id: threadId.value
12219
12773
  }, mode);
12220
12774
  if (!result) return;
12221
- const responseThreadId = configString(result.thread_id);
12222
- if (!responseThreadId || result.thread === void 0) return writeFailure(command, serviceError("Comment was changed but the response had no thread."), mode, 1);
12775
+ const actionResponse = isContract(COMMENT_ACTION_RESPONSE_SCHEMA, result) ? result : null;
12776
+ const actionRaw = isRecord$1(result) ? result : null;
12777
+ const responseThreadId = configString(actionResponse?.thread_id ?? actionRaw?.thread_id);
12778
+ const thread = actionResponse?.thread ?? actionRaw?.thread;
12779
+ if (!responseThreadId || thread === void 0) return writeFailure(command, serviceError("Comment was changed but the response had no thread."), mode, 1);
12223
12780
  writeSuccess(command, {
12224
12781
  artifact_id: target.artifactId,
12225
- share_url: configString(result.share_url),
12782
+ share_url: configString(actionResponse?.share_url ?? actionRaw?.share_url),
12226
12783
  thread_id: responseThreadId,
12227
- thread: result.thread
12784
+ thread
12228
12785
  }, mode);
12229
12786
  }
12230
12787
  async function postCommentAction(parsed, command, artifactId, payload, mode) {
@@ -12409,17 +12966,21 @@ async function runDoctor(parsed, mode) {
12409
12966
  return writeSuccess(command, doctorDataWithNextCommand(data), mode);
12410
12967
  }
12411
12968
  data.network.ok = true;
12412
- const body = result.data.body;
12969
+ const rawBody = result.data.body;
12970
+ const body = isContract(CLI_DOCTOR_RESPONSE_SCHEMA, rawBody) ? rawBody : isRecord$1(rawBody) ? rawBody : null;
12413
12971
  if (!body) throw new Error("Doctor response was not valid JSON.");
12414
- data.auth.ok = body.auth?.ok ?? true;
12415
- data.auth.email = body.user?.email ?? null;
12416
- const authority = doctorAuthority(body.auth?.authority);
12972
+ const auth = isRecord$1(body.auth) ? body.auth : null;
12973
+ const user = isRecord$1(body.user) ? body.user : null;
12974
+ const upload = isRecord$1(body.upload) ? body.upload : null;
12975
+ data.auth.ok = typeof auth?.ok === "boolean" ? auth.ok : true;
12976
+ data.auth.email = typeof user?.email === "string" ? user.email : null;
12977
+ const authority = doctorAuthority(auth?.authority);
12417
12978
  if (authority) data.auth.authority = authority;
12418
12979
  applyAgentDestinationDiagnostic(data, authority);
12419
12980
  data.upload.checked = true;
12420
- data.upload.ok = body.upload?.ok ?? false;
12981
+ data.upload.ok = upload?.ok === true;
12421
12982
  if (!data.upload.ok) {
12422
- data.upload.code = normalizeApiCode(body.upload?.code);
12983
+ data.upload.code = normalizeApiCode(upload?.code);
12423
12984
  data.upload.hint = uploadBlockedHint(data.upload.code);
12424
12985
  }
12425
12986
  return writeSuccess(command, doctorDataWithNextCommand(data), mode);
@@ -12896,8 +13457,14 @@ async function runProjectDownload(parsed, mode, projectId, isRetry = false) {
12896
13457
  }),
12897
13458
  authFailure: response.status === 401
12898
13459
  };
12899
- if (!body || !Array.isArray(body.artifacts) || typeof body.has_more !== "boolean") return { error: serviceError("Artifact list response was invalid.") };
12900
- return { data: body };
13460
+ const contracted = ARTIFACTS_LIST_RESPONSE_SCHEMA.safeParse(body);
13461
+ const raw = isRecord$1(body) ? body : null;
13462
+ if (!contracted.success && (!raw || !Array.isArray(raw.artifacts) || typeof raw.has_more !== "boolean")) return { error: serviceError("Artifact list response was invalid.") };
13463
+ return { data: contracted.success ? contracted.data : {
13464
+ artifacts: raw.artifacts,
13465
+ has_more: raw.has_more,
13466
+ next_cursor: typeof raw.next_cursor === "string" || raw.next_cursor === null ? raw.next_cursor : void 0
13467
+ } };
12901
13468
  };
12902
13469
  const entries = [];
12903
13470
  let cursor;
@@ -13124,41 +13691,19 @@ function normalizedEmailOptions(value) {
13124
13691
  return { values };
13125
13692
  }
13126
13693
  function parseEditData(body) {
13127
- if (!isRecord$1(body)) return null;
13128
- const artifact = body.artifact;
13129
- const destination = body.destination;
13130
- const share = body.share;
13131
- if (!isRecord$1(artifact) || !isRecord$1(destination) || !isRecord$1(share)) return null;
13132
- if (typeof artifact.id !== "string" || typeof body.title !== "string" || typeof destination.type !== "string" || typeof share.visibility !== "string") return null;
13133
- const base = {
13694
+ const result = CLI_EDIT_RESPONSE_SCHEMA.safeParse(body);
13695
+ if (!result.success) return null;
13696
+ return {
13697
+ ...result.data,
13134
13698
  artifact: {
13135
- id: artifact.id,
13136
- url: typeof artifact.url === "string" ? artifact.url : null
13699
+ ...result.data.artifact,
13700
+ url: result.data.artifact.url ?? null
13137
13701
  },
13138
- title: body.title,
13139
13702
  share: {
13140
- visibility: share.visibility,
13141
- link_expires_at: typeof share.link_expires_at === "string" || share.link_expires_at === null ? share.link_expires_at : null
13142
- }
13143
- };
13144
- if (destination.type === "project") {
13145
- if (typeof destination.project_id !== "string") return null;
13146
- return {
13147
- ...base,
13148
- destination: {
13149
- type: "project",
13150
- project_id: destination.project_id
13151
- }
13152
- };
13153
- }
13154
- if (destination.type === "home" && destination.project_id === null) return {
13155
- ...base,
13156
- destination: {
13157
- type: "home",
13158
- project_id: null
13703
+ ...result.data.share,
13704
+ link_expires_at: result.data.share.link_expires_at ?? null
13159
13705
  }
13160
13706
  };
13161
- return null;
13162
13707
  }
13163
13708
  //#endregion
13164
13709
  //#region src/git-exclude.ts
@@ -13375,7 +13920,7 @@ async function runMove(parsed, mode) {
13375
13920
  const request = await requestConfig(parsed.options);
13376
13921
  if (request.error) return writeFailure(command, request.error, mode, 1);
13377
13922
  const result = await runAuthenticatedApi(credential, parsed.options, async (current) => {
13378
- const moved = await apiPost(`/api/cli/shareables/${encodeURIComponent(target.artifactId)}/move`, current.token, { destination: home ? "home" : { project_id: projectId } }, parsed.options, request.init, {
13923
+ const moved = await apiPost(`/api/cli/shareables/${encodeURIComponent(target.artifactId)}/move`, current.token, buildMovePayload(home, projectId), parsed.options, request.init, {
13379
13924
  artifactTarget: true,
13380
13925
  credentialSource: current.source,
13381
13926
  profile: current.profile,
@@ -13389,45 +13934,19 @@ async function runMove(parsed, mode) {
13389
13934
  if (!data) return writeFailure(command, serviceError("Move succeeded but the response did not include move data."), mode, 1);
13390
13935
  writeSuccess(command, data, mode);
13391
13936
  }
13937
+ function buildMovePayload(home, projectId) {
13938
+ return { destination: home ? "home" : { project_id: projectId } };
13939
+ }
13392
13940
  function parseMoveData(body) {
13393
- if (!isRecord$1(body)) return null;
13394
- const artifact = body.artifact;
13395
- const destination = body.destination;
13396
- const share = body.share;
13397
- if (!isRecord$1(artifact) || !isRecord$1(destination) || !isRecord$1(share)) return null;
13398
- if (typeof artifact.id !== "string" || typeof destination.type !== "string" || typeof share.visibility !== "string" || typeof share.project_audience_may_change !== "boolean") return null;
13399
- if (destination.type === "project") {
13400
- if (typeof destination.project_id !== "string") return null;
13401
- return {
13402
- artifact: {
13403
- id: artifact.id,
13404
- url: typeof artifact.url === "string" ? artifact.url : null
13405
- },
13406
- destination: {
13407
- type: "project",
13408
- project_id: destination.project_id
13409
- },
13410
- share: {
13411
- visibility: share.visibility,
13412
- project_audience_may_change: share.project_audience_may_change
13413
- }
13414
- };
13415
- }
13416
- if (destination.type === "home" && destination.project_id === null) return {
13941
+ const result = CLI_MOVE_RESPONSE_SCHEMA.safeParse(body);
13942
+ if (!result.success) return null;
13943
+ return {
13944
+ ...result.data,
13417
13945
  artifact: {
13418
- id: artifact.id,
13419
- url: typeof artifact.url === "string" ? artifact.url : null
13420
- },
13421
- destination: {
13422
- type: "home",
13423
- project_id: null
13424
- },
13425
- share: {
13426
- visibility: share.visibility,
13427
- project_audience_may_change: share.project_audience_may_change
13946
+ ...result.data.artifact,
13947
+ url: result.data.artifact.url ?? null
13428
13948
  }
13429
13949
  };
13430
- return null;
13431
13950
  }
13432
13951
  //#endregion
13433
13952
  //#region src/command-runners/profiles.ts
@@ -13575,16 +14094,17 @@ async function importBotTokenProfile(command, profile, token, parsed, mode) {
13575
14094
  if (response.status === 401) return writeFailure(command, botTokenInvalidError(profile), mode, 1);
13576
14095
  return writeFailure(command, mapApiError(response.status, body, { baseUrl: baseUrlOf(parsed.options) }), mode, 1);
13577
14096
  }
13578
- if (typeof body?.access_token !== "string" || body.access_token.length === 0 || typeof body.expires_at !== "string" || typeof body.refresh_token !== "string" || !body.refresh_token || typeof body.refresh_token_expires_at !== "string") return writeFailure(command, validationError("The refresh response was invalid.", "Ask a workspace administrator to reissue the bot token, then retry with the new token.", "service_error"), mode, 1);
14097
+ const refresh = RotatingCliAuthRefreshResponseSchema.safeParse(body);
14098
+ if (!refresh.success || refresh.data.token_type.toLowerCase() !== "bearer") return writeFailure(command, validationError("The refresh response was invalid.", "Ask a workspace administrator to reissue the bot token, then retry with the new token.", "service_error"), mode, 1);
13579
14099
  const saved = await saveProfileSessionCredential(profile, {
13580
14100
  kind: "session",
13581
- session_token: body.access_token,
13582
- refresh_token: body.refresh_token,
13583
- expires_at: body.expires_at,
13584
- refresh_credential_expires_at: body.refresh_token_expires_at
14101
+ session_token: refresh.data.access_token,
14102
+ refresh_token: refresh.data.refresh_token,
14103
+ expires_at: refresh.data.expires_at,
14104
+ refresh_credential_expires_at: refresh.data.refresh_token_expires_at
13585
14105
  }, parsed.options);
13586
14106
  if (!saved.ok) return writeFailure(command, validationError("The rotated bot credential could not be stored; the imported token is now consumed and lost.", "Fix the token store, ask a workspace administrator to reissue the bot token, and import the new token.", "token_store_unavailable"), mode, 1);
13587
- const whoamiResult = await apiGet("/api/cli/whoami", body.access_token, parsed.options, request.init, {
14107
+ const whoamiResult = await apiGet("/api/cli/whoami", refresh.data.access_token, parsed.options, request.init, {
13588
14108
  authenticated: true,
13589
14109
  baseUrl: baseUrlOf(parsed.options)
13590
14110
  });
@@ -13688,14 +14208,17 @@ async function runShare(parsed, mode, isRetry = false) {
13688
14208
  if (parsed.options.linkExpiresAt !== void 0) initialForm.set("link_expires_at", parsed.options.linkExpiresAt);
13689
14209
  else if (parsed.options.noLinkExpiry === true) initialForm.set("link_expires_at", "null");
13690
14210
  if (parsed.options.noSlackNotify === true) initialForm.set("slack_notify", "false");
13691
- const uploadUrl = apiUrl("/api/shareables/uploads", baseUrl);
13692
- if (shareKey !== null) uploadUrl.searchParams.set("publish_key", shareKey);
14211
+ const uploadQuery = {};
14212
+ if (shareKey !== null) uploadQuery.publish_key = shareKey;
14213
+ if (parsed.options.expectedVersion) uploadQuery.expected_version = parsed.options.expectedVersion;
13693
14214
  const upload = await prepareUploadPayload(targetPath, fileStat, initialForm);
13694
14215
  if (upload.error) return writeFailure(command, upload.error, mode, 1);
13695
14216
  if (upload.payload.kind === "static_site") {
13696
- uploadUrl.searchParams.set("artifact_kind", "static_site");
13697
- if (destination.containerId) uploadUrl.searchParams.set("container_id", destination.containerId);
14217
+ uploadQuery.artifact_kind = "static_site";
14218
+ if (destination.containerId) uploadQuery.container_id = destination.containerId;
13698
14219
  }
14220
+ const uploadUrl = apiUrl("/api/shareables/uploads", baseUrl);
14221
+ for (const [key, value] of Object.entries(uploadQuery)) if (value !== void 0) uploadUrl.searchParams.set(key, value);
13699
14222
  const uploaded = await postShareUpload({
13700
14223
  uploadUrl,
13701
14224
  token: credential.token,
@@ -13703,6 +14226,10 @@ async function runShare(parsed, mode, isRetry = false) {
13703
14226
  requestInit: request.init,
13704
14227
  errorOptions: {
13705
14228
  authenticated: true,
14229
+ ...shareKey !== null ? {
14230
+ artifactTarget: true,
14231
+ operation: "share"
14232
+ } : {},
13706
14233
  baseUrl,
13707
14234
  credentialSource: credential.source,
13708
14235
  profile: credential.profile,
@@ -13797,6 +14324,8 @@ async function runUpdate(parsed, mode, isRetry = false) {
13797
14324
  if (unsupportedOption) return writeFailure(command, validationError(`Update does not accept --${unsupportedOption}.`, "Update only adds a new version. Remove unsupported options and retry."), mode, 1);
13798
14325
  const artifactId = resolveArtifactId(artifactInput);
13799
14326
  if (!artifactId) return writeFailure(command, targetResolutionError(artifactInput, "update"), mode, 1);
14327
+ const label = VersionLabelInputSchema.optional().safeParse(parsed.options.label);
14328
+ if (!label.success) return writeFailure(command, validationError("Invalid version label.", label.error.issues[0]?.message ?? "Check the label and retry."), mode, 1);
13800
14329
  const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
13801
14330
  if (!credential.ok) return handleCredentialFailure(command, credential, parsed.options, mode, () => runUpdate(parsed, mode, true), isRetry);
13802
14331
  const fileStat = await stat(targetPath).catch(() => null);
@@ -13806,8 +14335,11 @@ async function runUpdate(parsed, mode, isRetry = false) {
13806
14335
  if (request.error) return writeFailure(command, request.error, mode, 1);
13807
14336
  const upload = await prepareUploadPayload(targetPath, fileStat);
13808
14337
  if (upload.error) return writeFailure(command, upload.error, mode, 1);
14338
+ const updateQuery = label.data !== void 0 ? { label: label.data } : {};
14339
+ if (upload.payload.kind === "static_site") updateQuery.artifact_kind = "static_site";
14340
+ if (parsed.options.expectedVersion) updateQuery.expected_version = parsed.options.expectedVersion;
13809
14341
  const updateUrl = apiUrl(`/api/shareables/${encodeURIComponent(artifactId)}/versions`, baseUrl);
13810
- if (upload.payload.kind === "static_site") updateUrl.searchParams.set("artifact_kind", "static_site");
14342
+ for (const [key, value] of Object.entries(updateQuery)) if (value !== void 0) updateUrl.searchParams.set(key, value);
13811
14343
  const response = await cliFetch(updateUrl, {
13812
14344
  method: "POST",
13813
14345
  headers: { Authorization: `Bearer ${credential.token}` },
@@ -13819,20 +14351,26 @@ async function runUpdate(parsed, mode, isRetry = false) {
13819
14351
  if (!response.ok) return handleAuthenticatedCredentialFailure(command, mapApiError(response.status, body, {
13820
14352
  authenticated: true,
13821
14353
  artifactTarget: true,
14354
+ operation: "update",
13822
14355
  baseUrl,
13823
14356
  credentialSource: credential.source,
13824
14357
  profile: credential.profile,
13825
14358
  profileCredentialKind: credential.profileCredentialKind,
13826
14359
  botProfile: credential.botProfile
13827
14360
  }), credential, parsed.options, mode, () => runUpdate(parsed, mode, true), isRetry);
13828
- const id = body?.id ?? artifactId;
14361
+ const responseBody = isContract(ARTIFACT_VERSION_UPDATE_RESPONSE_SCHEMA, body) ? body : null;
14362
+ const id = responseBody?.id ?? artifactId;
13829
14363
  const result = {
13830
14364
  artifact: {
13831
14365
  id,
13832
- url: body?.shareUrl ?? (id ? `${baseUrl.replace(/\/$/, "")}/a/${id}` : null),
13833
- kind: body?.artifactKind ?? upload.payload.kind
14366
+ url: responseBody?.shareUrl ?? (id ? `${baseUrl.replace(/\/$/, "")}/a/${id}` : null),
14367
+ kind: responseBody?.artifactKind ?? upload.payload.kind
14368
+ },
14369
+ version: {
14370
+ ...responseBody?.number !== void 0 ? { number: responseBody.number } : {},
14371
+ id: responseBody?.versionId ?? null,
14372
+ label: responseBody?.label !== void 0 ? responseBody.label : label.data ?? null
13834
14373
  },
13835
- version: { id: body?.versionId ?? null },
13836
14374
  result: { updated: true }
13837
14375
  };
13838
14376
  if (!updateSuccessFields(result)) return writeFailure(command, serviceError("Update succeeded but the response did not include an artifact id, URL, and version id."), mode, 1);
@@ -13882,13 +14420,14 @@ async function runAppend(parsed, mode, isRetry = false) {
13882
14420
  profileCredentialKind: credential.profileCredentialKind,
13883
14421
  botProfile: credential.botProfile
13884
14422
  }), credential, parsed.options, mode, () => runAppend(parsed, mode, true), isRetry);
14423
+ const responseBody = isContract(ARTIFACT_APPEND_RESPONSE_SCHEMA, body) ? body : null;
13885
14424
  const success = {
13886
14425
  artifact: {
13887
- id: body?.id ?? id,
13888
- url: body?.shareUrl ?? `${baseUrlOf(parsed.options)}/a/${id}`,
13889
- kind: body?.artifactKind
14426
+ id: responseBody?.id ?? id,
14427
+ url: responseBody?.shareUrl ?? `${baseUrlOf(parsed.options)}/a/${id}`,
14428
+ kind: responseBody?.artifactKind
13890
14429
  },
13891
- version: { id: body?.versionId },
14430
+ version: { id: responseBody?.versionId },
13892
14431
  result: { appended: true }
13893
14432
  };
13894
14433
  if (!updateSuccessFields(success)) return writeFailure(command, validationError("Append succeeded but the response was incomplete.", "Retry the command."), mode, 1);
@@ -13913,8 +14452,10 @@ async function runWhoami(parsed, mode) {
13913
14452
  });
13914
14453
  if (whoami.error) return writeFailure(command, whoami.error, mode, 1);
13915
14454
  const renewal = await renewalDetails(credential, parsed.options);
13916
- return writeSuccess(command, isRecord$1(whoami.data) ? {
13917
- ...whoami.data,
14455
+ const identity = CLI_WHOAMI_RESPONSE_SCHEMA.safeParse(whoami.data);
14456
+ const data = identity.success ? identity.data : isRecord$1(whoami.data) ? whoami.data : null;
14457
+ return writeSuccess(command, data ? {
14458
+ ...data,
13918
14459
  credential_source: credential.source,
13919
14460
  ...renewal
13920
14461
  } : {
@@ -14156,6 +14697,7 @@ async function logoutRunner(ctx) {
14156
14697
  }
14157
14698
  async function updateRunner(ctx) {
14158
14699
  const parsed = parsedArgsFromContext("update", ctx);
14700
+ if (ctx.tokens.filter((token) => token.kind === "option" && token.name === "label").length > 1) return writeFailure("update", validationError("Invalid version label.", "Pass --label once."), outputMode(parsed.options), 1);
14159
14701
  return await runWithSkillAutoUpdate(parsed, () => runUpdate(parsed, outputMode(parsed.options)));
14160
14702
  }
14161
14703
  async function appendRunner(ctx) {
@@ -14166,8 +14708,9 @@ async function editRunner(ctx) {
14166
14708
  const parsed = parsedArgsFromContext("edit", ctx);
14167
14709
  return await runWithSkillAutoUpdate(parsed, () => runEdit(parsed, outputMode(parsed.options)));
14168
14710
  }
14169
- async function deleteRunner(ctx) {
14170
- const parsed = parsedArgsFromContext("delete", ctx);
14711
+ async function deleteRunner(ctx, invocationPath = "delete") {
14712
+ const parsed = parsedArgsFromContext(invocationPath, ctx);
14713
+ parsed.command = "delete";
14171
14714
  return await runWithSkillAutoUpdate(parsed, () => runDelete(parsed, outputMode(parsed.options)));
14172
14715
  }
14173
14716
  async function resolveRunner(ctx) {
@@ -14512,7 +15055,7 @@ Common failures:
14512
15055
  auth_required Use ${TOKEN_ENV_VAR} or ${TOKEN_OPTION}; tokens are issued at ${DEFAULT_BASE_URL}/settings/tokens
14513
15056
  invalid_destination Choose --project-id <id> or --home
14514
15057
  target_not_found Use an artifact ID, share URL, or sandbox URL
14515
- upload_not_allowed Sharing is temporarily unavailable; contact Artifact Share support`,
15058
+ self_upload_disabled Sign in with Google or Microsoft to upload your own files`,
14516
15059
  run: () => {}
14517
15060
  });
14518
15061
  const loginDefinition = define({
@@ -14613,6 +15156,11 @@ const shareDefinition = define({
14613
15156
  type: "string",
14614
15157
  toKebab: true,
14615
15158
  description: "Stable key for create-or-update: the first share creates the artifact, repeats add versions. Not a secret; it appears in logs and JSON"
15159
+ },
15160
+ expectedVersion: {
15161
+ type: "string",
15162
+ toKebab: true,
15163
+ description: "Require this current version when --key updates an existing artifact"
14616
15164
  }
14617
15165
  },
14618
15166
  examples: `npm exec --yes --package=@artifactshare/cli -- artifactshare share report.html --project-id <id> --json
@@ -14638,7 +15186,7 @@ For repeat jobs, use --key: first share creates the artifact, later runs add ver
14638
15186
 
14639
15187
  Common failures:
14640
15188
  auth_required Set ARTIFACTSHARE_TOKEN before share
14641
- upload_not_allowed Publishing is temporarily unavailable; contact Artifact Share support
15189
+ self_upload_disabled Sign in with Google or Microsoft to upload your own files
14642
15190
  file_too_large Reduce file or directory size and retry
14643
15191
  validation_failed Check file type (.html / .md for single files) and directory layout
14644
15192
  key_target_moved The artifact for --key moved; update it by ID or use a new key
@@ -14650,25 +15198,50 @@ const updateDefinition = define({
14650
15198
  toKebab: true,
14651
15199
  args: {
14652
15200
  ...commonArgs,
15201
+ json: {
15202
+ ...commonArgs.json,
15203
+ description: "Print stable JSON output; data.version.number matches the Viewer version number; data.version.label is the stored label or null when omitted"
15204
+ },
14653
15205
  artifactIdOrUrl: {
14654
15206
  type: "positional",
14655
15207
  toKebab: true,
14656
- description: "Artifact ID, /a/<id> share URL, or <id>.sandbox.* URL"
15208
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14657
15209
  },
14658
15210
  path: {
14659
15211
  type: "positional",
14660
15212
  description: "File or directory to add as the new version"
15213
+ },
15214
+ label: {
15215
+ type: "string",
15216
+ description: "Optional version note (1–80 Unicode code points; NFC normalized, outer spaces trimmed)"
15217
+ },
15218
+ expectedVersion: {
15219
+ type: "string",
15220
+ toKebab: true,
15221
+ description: "Only update when this is still the current version id; required for agent-preset logins"
14661
15222
  }
14662
15223
  },
14663
15224
  examples: `Target:
14664
- Accepts an artifact ID, /a/<id> share URL, or <id>.sandbox.* URL.
15225
+ Accepts an artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL.
14665
15226
  Titles and project names are not updated directly; resolve them to an ID first.
14666
15227
 
15228
+ Access:
15229
+ You can update your own artifact or another artifact you have collaborative access to.
15230
+ A verified external viewer can update an artifact explicitly shared with their email
15231
+ when the artifact workspace allows external posting.
15232
+
15233
+ After login --preset agent, pass --expected-version <version-id> using
15234
+ data.version.id from the previous successful share or update output.
15235
+
15236
+ JSON output:
15237
+ Successful JSON includes the stored label at data.version.label, or null when omitted. data.version.number matches the Viewer version number (v{number}); older servers may omit it.
15238
+
14667
15239
  Common failures:
15240
+ expected_version_required Pass --expected-version <version-id>, using data.version.id from the previous successful share or update output.
14668
15241
  auth_required Set ARTIFACTSHARE_TOKEN before update
14669
15242
  target_not_found Retry with an artifact ID, share URL, or sandbox URL
14670
15243
  artifact_kind_mismatch Use a file for single-file artifacts or a directory for static sites
14671
- upload_not_allowed Publishing is temporarily unavailable; contact Artifact Share support
15244
+ self_upload_disabled Sign in with Google or Microsoft to upload your own files
14672
15245
  file_too_large Reduce file or directory size and retry
14673
15246
  validation_failed Check file type (.html / .md for single files) and directory layout`
14674
15247
  });
@@ -14699,7 +15272,7 @@ const editDefinition = define({
14699
15272
  artifactIdOrUrl: {
14700
15273
  type: "positional",
14701
15274
  toKebab: true,
14702
- description: "Artifact ID, /a/<id> share URL, or <id>.sandbox.* URL"
15275
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14703
15276
  },
14704
15277
  title: {
14705
15278
  type: "string",
@@ -14771,7 +15344,7 @@ const deleteDefinition = define({
14771
15344
  artifactIdOrUrl: {
14772
15345
  type: "positional",
14773
15346
  toKebab: true,
14774
- description: "Artifact ID, /a/<id> share URL, or <id>.sandbox.* URL"
15347
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14775
15348
  }
14776
15349
  },
14777
15350
  examples: `npm exec --yes --package=@artifactshare/cli -- artifactshare delete abc123def4 --json
@@ -14817,7 +15390,7 @@ const downloadDefinition = define({
14817
15390
  type: "positional",
14818
15391
  toKebab: true,
14819
15392
  required: false,
14820
- description: "Artifact ID, /a/<id> share URL, or <id>.sandbox.* URL"
15393
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14821
15394
  },
14822
15395
  projectId: {
14823
15396
  type: "string",
@@ -14857,7 +15430,7 @@ const openDefinition = define({
14857
15430
  artifactIdOrUrl: {
14858
15431
  type: "positional",
14859
15432
  toKebab: true,
14860
- description: "Artifact ID, /a/<id> share URL, or <id>.sandbox.* URL"
15433
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14861
15434
  }
14862
15435
  },
14863
15436
  examples: `npm exec --yes --package=@artifactshare/cli -- artifactshare open https://artifactshare.com/a/abc123def4 --json
@@ -14886,7 +15459,7 @@ const moveDefinition = define({
14886
15459
  artifactIdOrUrl: {
14887
15460
  type: "positional",
14888
15461
  toKebab: true,
14889
- description: "Artifact ID or /a/<id> share URL"
15462
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14890
15463
  },
14891
15464
  projectId: {
14892
15465
  type: "string",
@@ -14921,7 +15494,7 @@ const artifactsGetDefinition = define({
14921
15494
  artifactIdOrUrl: {
14922
15495
  type: "positional",
14923
15496
  toKebab: true,
14924
- description: "Artifact ID, /a/<id> share URL, or <id>.sandbox.* URL"
15497
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14925
15498
  },
14926
15499
  offset: {
14927
15500
  type: "string",
@@ -14990,18 +15563,21 @@ Common failures:
14990
15563
  });
14991
15564
  const artifactsDefinition = define({
14992
15565
  name: "artifacts",
14993
- description: "Read Artifact Share artifacts.",
15566
+ description: "List, read, and delete Artifact Share artifacts.",
14994
15567
  toKebab: true,
14995
15568
  args: commonArgs,
14996
15569
  subCommands: {
14997
15570
  list: lazyCommand(artifactsListDefinition, artifactsListRunner),
14998
- get: lazyCommand(artifactsGetDefinition, artifactsGetRunner)
15571
+ get: lazyCommand(artifactsGetDefinition, artifactsGetRunner),
15572
+ delete: lazyCommand(deleteDefinition, (ctx) => deleteRunner(ctx, "artifacts delete"))
14999
15573
  },
15000
15574
  examples: `npm exec --yes --package=@artifactshare/cli -- artifactshare artifacts list --json
15001
15575
  npm exec --yes --package=@artifactshare/cli -- artifactshare artifacts get <artifact-id-or-url> --json
15002
15576
 
15003
15577
  Use artifacts list to find IDs for update, edit, move, delete, artifacts get, and comments list.
15004
- Use artifacts get to read back Markdown or HTML before update.`,
15578
+ Use artifacts get to read back Markdown or HTML before update.
15579
+ Use artifacts delete as an alias of top-level delete:
15580
+ npm exec --yes --package=@artifactshare/cli -- artifactshare artifacts delete <artifact-id-or-url> --json`,
15005
15581
  run: parentCommandRunner("artifacts")
15006
15582
  });
15007
15583
  const commentsListDefinition = define({
@@ -15013,7 +15589,7 @@ const commentsListDefinition = define({
15013
15589
  artifactIdOrUrl: {
15014
15590
  type: "positional",
15015
15591
  toKebab: true,
15016
- description: "Artifact ID, /a/<id> share URL, or <id>.sandbox.* URL"
15592
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
15017
15593
  }
15018
15594
  },
15019
15595
  examples: `npm exec --yes --package=@artifactshare/cli -- artifactshare comments list abc123def4 --json
@@ -15034,7 +15610,7 @@ const commentsPostDefinition = define({
15034
15610
  artifactIdOrUrl: {
15035
15611
  type: "positional",
15036
15612
  toKebab: true,
15037
- description: "Artifact ID, /a/<id> share URL, or <id>.sandbox.* URL"
15613
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
15038
15614
  },
15039
15615
  body: {
15040
15616
  type: "string",
@@ -15086,7 +15662,7 @@ const commentThreadActionArgs = {
15086
15662
  artifactIdOrUrl: {
15087
15663
  type: "positional",
15088
15664
  toKebab: true,
15089
- description: "Artifact ID, /a/<id> share URL, or <id>.sandbox.* URL"
15665
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
15090
15666
  },
15091
15667
  threadId: {
15092
15668
  type: "string",
@@ -15099,7 +15675,7 @@ const commentMessageActionArgs = {
15099
15675
  artifactIdOrUrl: {
15100
15676
  type: "positional",
15101
15677
  toKebab: true,
15102
- description: "Artifact ID, /a/<id> share URL, or <id>.sandbox.* URL"
15678
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
15103
15679
  },
15104
15680
  messageId: {
15105
15681
  type: "string",
@@ -15586,7 +16162,7 @@ The response includes project.id and next_command for share --project-id.
15586
16162
 
15587
16163
  Common failures:
15588
16164
  auth_required Set ARTIFACTSHARE_TOKEN before projects create
15589
- upload_not_allowed Publishing is temporarily unavailable; contact Artifact Share support
16165
+ self_upload_disabled Sign in with Google or Microsoft to upload your own files
15590
16166
  project_name_conflict Choose another name or archive the existing project first
15591
16167
  validation_failed Pass a non-empty name and valid --visibility`
15592
16168
  });