@nesso-how/plugin 0.0.0-stage → 0.1.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.
@@ -0,0 +1,764 @@
1
+ import { a as parseOrThrow, i as PluginError, n as isAbsoluteIri, r as relationKey, t as createWriteCommands } from "./commands-xXIv9QeH.js";
2
+ import { z } from "zod";
3
+ //#region ../schema/src/validate.ts
4
+ function validateGraph(graph) {
5
+ const issues = [];
6
+ const concepts = /* @__PURE__ */ new Set();
7
+ const types = /* @__PURE__ */ new Set();
8
+ const relations = /* @__PURE__ */ new Set();
9
+ for (const [index, concept] of graph.concepts.entries()) {
10
+ if (!isAbsoluteIri(concept.id)) issues.push({
11
+ path: `concepts[${index}].id`,
12
+ message: `Expected an absolute IRI: ${concept.id}`
13
+ });
14
+ else if (concepts.has(concept.id)) issues.push({
15
+ path: `concepts[${index}].id`,
16
+ message: `Duplicate concept IRI: ${concept.id}`
17
+ });
18
+ concepts.add(concept.id);
19
+ if (concept.description !== void 0 && typeof concept.description !== "string") issues.push({
20
+ path: `concepts[${index}].description`,
21
+ message: "Expected a string"
22
+ });
23
+ if (!Number.isFinite(concept.position.x) || !Number.isFinite(concept.position.y)) issues.push({
24
+ path: `concepts[${index}].position`,
25
+ message: `Invalid position: ${concept.id}`
26
+ });
27
+ if (concept.color !== void 0 && !/^#[0-9a-fA-F]{6}$/.test(concept.color)) issues.push({
28
+ path: `concepts[${index}].color`,
29
+ message: `Invalid color: ${concept.id}`
30
+ });
31
+ }
32
+ for (const [index, type] of graph.relationTypes.entries()) {
33
+ if (!isAbsoluteIri(type.id)) issues.push({
34
+ path: `relationTypes[${index}].id`,
35
+ message: `Expected an absolute IRI: ${type.id}`
36
+ });
37
+ else if (types.has(type.id) || concepts.has(type.id)) issues.push({
38
+ path: `relationTypes[${index}].id`,
39
+ message: `Duplicate relation IRI: ${type.id}`
40
+ });
41
+ types.add(type.id);
42
+ }
43
+ for (const [index, relation] of graph.relations.entries()) {
44
+ if (!concepts.has(relation.source) || !concepts.has(relation.target)) issues.push({
45
+ path: `relations[${index}]`,
46
+ message: `Unknown concept in relation: ${relationKey(relation)}`
47
+ });
48
+ if (!types.has(relation.predicate)) issues.push({
49
+ path: `relations[${index}].predicate`,
50
+ message: `Unknown relation type: ${relation.predicate}`
51
+ });
52
+ const key = relationKey(relation);
53
+ if (relations.has(key)) issues.push({
54
+ path: `relations[${index}]`,
55
+ message: `Duplicate relation: ${key}`
56
+ });
57
+ relations.add(key);
58
+ }
59
+ return issues;
60
+ }
61
+ //#endregion
62
+ //#region src/definitions.ts
63
+ const themeColors = [
64
+ "background",
65
+ "foreground",
66
+ "canvas",
67
+ "sidebar",
68
+ "primary",
69
+ "primary-hover",
70
+ "primary-foreground",
71
+ "muted",
72
+ "muted-foreground",
73
+ "hover",
74
+ "pressed",
75
+ "border",
76
+ "ring",
77
+ "selection-halo",
78
+ "node-border",
79
+ "edge",
80
+ "handle"
81
+ ];
82
+ const contributionId = z.string().max(64).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/);
83
+ const color = z.string().regex(/^#[\da-fA-F]{6}([\da-fA-F]{2})?$/);
84
+ const fontFace = z.strictObject({
85
+ path: z.string().max(240).regex(/^(?:[\w-]+\/)*[\w-]+\.woff2$/),
86
+ weight: z.tuple([z.number().int().min(1).max(1e3), z.number().int().min(1).max(1e3)]).refine(([min, max]) => min <= max),
87
+ style: z.enum(["normal", "italic"]),
88
+ unicodeRange: z.array(z.tuple([z.number().int().min(0).max(1114111), z.number().int().min(0).max(1114111)]).refine(([min, max]) => min <= max)).min(1).max(64).optional()
89
+ });
90
+ const font = z.strictObject({ faces: z.array(fontFace).max(32) });
91
+ const luminance = (value) => {
92
+ const linear = [
93
+ 1,
94
+ 3,
95
+ 5
96
+ ].map((offset) => parseInt(value.slice(offset, offset + 2), 16) / 255).map((value) => value <= .04045 ? value / 12.92 : ((value + .055) / 1.055) ** 2.4);
97
+ return linear[0] * .2126 + linear[1] * .7152 + linear[2] * .0722;
98
+ };
99
+ const opaque = (value) => value.length === 7 || value.slice(7).toLowerCase() === "ff";
100
+ const contrast = (left, right) => (Math.max(luminance(left), luminance(right)) + .05) / (Math.min(luminance(left), luminance(right)) + .05);
101
+ const themeDefinition = z.strictObject({
102
+ id: contributionId,
103
+ colors: z.strictObject(Object.fromEntries(themeColors.map((key) => [key, color]))),
104
+ metrics: z.strictObject({
105
+ "radius-control": z.number().min(0).max(16),
106
+ "radius-object": z.number().min(0).max(16),
107
+ "duration-state": z.number().int().min(0).max(300)
108
+ }),
109
+ fonts: z.strictObject({
110
+ sans: font,
111
+ mono: font
112
+ })
113
+ }).superRefine(({ colors, fonts }, context) => {
114
+ for (const key of [
115
+ "background",
116
+ "canvas",
117
+ "sidebar"
118
+ ]) {
119
+ if (!opaque(colors[key]) || luminance(colors[key]) < .8) context.addIssue({
120
+ code: "custom",
121
+ path: ["colors", key],
122
+ message: "Expected an opaque light surface"
123
+ });
124
+ if (!opaque(colors.foreground) || contrast(colors.foreground, colors[key]) < 4.5) context.addIssue({
125
+ code: "custom",
126
+ path: ["colors", "foreground"],
127
+ message: "Insufficient foreground contrast"
128
+ });
129
+ }
130
+ if (!opaque(colors.primary) || !opaque(colors["primary-foreground"]) || contrast(colors.primary, colors["primary-foreground"]) < 4.5) context.addIssue({
131
+ code: "custom",
132
+ path: ["colors", "primary-foreground"],
133
+ message: "Insufficient primary contrast"
134
+ });
135
+ if (fonts.sans.faces.length + fonts.mono.faces.length > 32) context.addIssue({
136
+ code: "custom",
137
+ path: ["fonts"],
138
+ message: "Font face limit exceeded"
139
+ });
140
+ });
141
+ const vocabDefinition = z.strictObject({
142
+ id: contributionId,
143
+ relationTypes: z.array(z.strictObject({
144
+ id: z.string().min(1).max(2048),
145
+ label: z.string().max(30)
146
+ })).min(1),
147
+ defaultTypeId: z.string().min(1).max(2048)
148
+ }).superRefine(({ relationTypes, defaultTypeId }, context) => {
149
+ for (const issue of validateGraph({
150
+ concepts: [],
151
+ relations: [],
152
+ relationTypes
153
+ })) context.addIssue({
154
+ code: "custom",
155
+ path: ["relationTypes"],
156
+ message: issue.message
157
+ });
158
+ if (!relationTypes.some(({ id }) => id === defaultTypeId)) context.addIssue({
159
+ code: "custom",
160
+ path: ["defaultTypeId"],
161
+ message: "Default type must be offered by the vocabulary"
162
+ });
163
+ });
164
+ function parseDefinition(kind, value) {
165
+ return parseOrThrow(kind === "theme" ? themeDefinition : vocabDefinition, value);
166
+ }
167
+ //#endregion
168
+ //#region src/files.ts
169
+ const fileTextLimit = 16777216;
170
+ const mediaType = z.string().max(128).regex(/^[\w!#$&^.+-]+\/[\w!#$&^.+-]+$/);
171
+ const fileOpenOptions = z.strictObject({
172
+ extensions: z.array(z.string().regex(/^[a-zA-Z0-9]{1,16}$/)).min(1).max(16),
173
+ mimeTypes: z.array(mediaType).max(16)
174
+ });
175
+ const fileSaveOptions = z.strictObject({
176
+ name: z.string().trim().min(1).max(240).regex(/^[^/\\]+$/).refine((value) => value !== "." && value !== ".." && [...value].every((character) => character.charCodeAt(0) >= 32 && character.charCodeAt(0) !== 127)),
177
+ mediaType,
178
+ text: z.string().max(fileTextLimit).refine((value) => new TextEncoder().encode(value).byteLength <= fileTextLimit, "File text byte limit exceeded")
179
+ });
180
+ const fileOpenResult = z.strictObject({
181
+ name: z.string().min(1).max(240),
182
+ mediaType,
183
+ text: fileSaveOptions.shape.text
184
+ }).nullable();
185
+ function parseFileOptions(kind, value) {
186
+ return parseOrThrow(kind === "open" ? fileOpenOptions : fileSaveOptions, value);
187
+ }
188
+ //#endregion
189
+ //#region src/i18n.ts
190
+ const text = (limit) => z.string().max(limit).refine((value) => new TextEncoder().encode(value).byteLength <= limit, "Text byte limit exceeded");
191
+ const localizedText = (limit) => z.strictObject({
192
+ en: text(limit).min(1),
193
+ it: text(limit).min(1).optional(),
194
+ "zh-CN": text(limit).min(1).optional()
195
+ });
196
+ const resolvePluginText = (value, locale) => value[locale] ?? value.en;
197
+ //#endregion
198
+ //#region src/runtime.ts
199
+ const runtimeLimits = {
200
+ request: 33554432,
201
+ snapshot: 67108864,
202
+ pending: 64,
203
+ deadline: 3e4,
204
+ interaction: 3e5,
205
+ initialization: 1e4,
206
+ action: 12e4
207
+ };
208
+ const themeTokens = [
209
+ ...themeColors,
210
+ "font-sans",
211
+ "font-mono",
212
+ "radius-control",
213
+ "radius-object",
214
+ "duration-state"
215
+ ];
216
+ const id = z.string().min(1).max(2048);
217
+ const position = z.strictObject({
218
+ x: z.number(),
219
+ y: z.number()
220
+ });
221
+ const selection = z.array(z.strictObject({
222
+ kind: z.enum(["concept", "relation"]),
223
+ id
224
+ }));
225
+ const relationType = z.strictObject({
226
+ id,
227
+ label: z.string()
228
+ });
229
+ const locale = z.enum([
230
+ "en",
231
+ "it",
232
+ "zh-CN"
233
+ ]);
234
+ const operation = z.discriminatedUnion("kind", [
235
+ z.strictObject({
236
+ kind: z.literal("concept.label"),
237
+ id,
238
+ value: z.string()
239
+ }),
240
+ z.strictObject({
241
+ kind: z.literal("concept.description"),
242
+ id,
243
+ value: z.string()
244
+ }),
245
+ z.strictObject({
246
+ kind: z.literal("concept.color"),
247
+ id,
248
+ value: z.string()
249
+ }),
250
+ z.strictObject({
251
+ kind: z.literal("concept.position"),
252
+ id,
253
+ value: position
254
+ }),
255
+ z.strictObject({
256
+ kind: z.literal("concept.positions"),
257
+ updates: z.array(z.strictObject({
258
+ id,
259
+ position
260
+ }))
261
+ }),
262
+ z.strictObject({
263
+ kind: z.literal("concept.add"),
264
+ id,
265
+ position: position.optional()
266
+ }),
267
+ z.strictObject({
268
+ kind: z.literal("concept.remove"),
269
+ id
270
+ }),
271
+ z.strictObject({
272
+ kind: z.literal("relation.connect"),
273
+ source: id,
274
+ target: id,
275
+ type: relationType.optional()
276
+ }),
277
+ z.strictObject({
278
+ kind: z.literal("relation.reconnect"),
279
+ id,
280
+ source: id,
281
+ target: id
282
+ }),
283
+ z.strictObject({
284
+ kind: z.literal("relation.type"),
285
+ id,
286
+ typeId: id
287
+ }),
288
+ z.strictObject({
289
+ kind: z.literal("relation.type.create"),
290
+ id,
291
+ typeId: id,
292
+ label: z.string()
293
+ }),
294
+ z.strictObject({
295
+ kind: z.literal("relation.remove"),
296
+ id
297
+ }),
298
+ z.strictObject({
299
+ kind: z.literal("document.reset"),
300
+ id
301
+ }),
302
+ z.strictObject({ kind: z.literal("history.undo") }),
303
+ z.strictObject({ kind: z.literal("history.redo") }),
304
+ z.strictObject({
305
+ kind: z.literal("selection.set"),
306
+ value: selection
307
+ }),
308
+ z.strictObject({
309
+ kind: z.literal("view.activate"),
310
+ id: id.nullable()
311
+ }),
312
+ z.strictObject({
313
+ kind: z.literal("view.create"),
314
+ id,
315
+ name: z.string(),
316
+ conceptIds: z.array(id)
317
+ }),
318
+ z.strictObject({
319
+ kind: z.literal("view.rename"),
320
+ id,
321
+ name: z.string()
322
+ }),
323
+ z.strictObject({
324
+ kind: z.literal("view.pin"),
325
+ id,
326
+ pinned: z.boolean()
327
+ }),
328
+ z.strictObject({
329
+ kind: z.literal("view.membership"),
330
+ viewId: id,
331
+ conceptId: id,
332
+ included: z.boolean()
333
+ }),
334
+ z.strictObject({
335
+ kind: z.literal("view.remove"),
336
+ id
337
+ }),
338
+ ...["vocab", "theme"].map((kind) => z.strictObject({
339
+ kind: z.literal(`preferences.${kind}`),
340
+ id
341
+ })),
342
+ z.strictObject({
343
+ kind: z.literal("preferences.locale"),
344
+ value: locale
345
+ }),
346
+ z.strictObject({
347
+ kind: z.literal("preferences.panels"),
348
+ value: z.strictObject({
349
+ explorerWidth: z.number(),
350
+ inspectorWidth: z.number()
351
+ })
352
+ }),
353
+ z.strictObject({
354
+ kind: z.literal("preferences.section"),
355
+ id: z.enum([
356
+ "sidebar",
357
+ "sidebar.pinned-views",
358
+ "sidebar.views",
359
+ "inspector",
360
+ "inspector.connections",
361
+ "inspector.views",
362
+ "inspector.nodes"
363
+ ]),
364
+ open: z.boolean()
365
+ })
366
+ ]);
367
+ const options = z.strictObject({
368
+ historyGroup: id.optional(),
369
+ atRevision: z.number().int().nonnegative().optional()
370
+ });
371
+ const metadata = z.strictObject({
372
+ name: localizedText(128),
373
+ description: localizedText(2048),
374
+ documentation: localizedText(16384)
375
+ });
376
+ const pluginI18n = z.object({ metadata }).catchall(localizedText(16384));
377
+ function parsePluginI18n(value) {
378
+ checkMessageSize(value, 65536);
379
+ return parseOrThrow(pluginI18n, value, "i18n.");
380
+ }
381
+ const manifestFields = { apiVersion: z.literal(1) };
382
+ const jsEntry = z.string().max(240).regex(/^(?:[\w-]+\/)*[\w-]+\.js$/);
383
+ const jsonEntry = z.string().max(240).regex(/^(?:[\w-]+\/)*[\w-]+\.json$/);
384
+ const operationDeclarations = z.array(z.enum([
385
+ "concept.label",
386
+ "concept.description",
387
+ "concept.color",
388
+ "concept.position",
389
+ "concept.positions",
390
+ "concept.add",
391
+ "concept.remove",
392
+ "relation.connect",
393
+ "relation.reconnect",
394
+ "relation.type",
395
+ "relation.type.create",
396
+ "relation.remove",
397
+ "selection.set",
398
+ "view.membership"
399
+ ]));
400
+ const manifest = z.discriminatedUnion("kind", [z.strictObject({
401
+ ...manifestFields,
402
+ kind: z.literal("actions"),
403
+ entry: jsEntry,
404
+ writes: operationDeclarations,
405
+ capabilities: z.array(z.enum([
406
+ "files.open",
407
+ "files.save",
408
+ "notifications.notify"
409
+ ]))
410
+ }), ...["theme", "vocab"].map((kind) => z.strictObject({
411
+ ...manifestFields,
412
+ kind: z.literal(kind),
413
+ entry: jsonEntry,
414
+ writes: z.tuple([]),
415
+ capabilities: z.tuple([])
416
+ }))]).refine((value) => new Set(value.writes).size === value.writes.length && new Set(value.capabilities).size === value.capabilities.length, "Declarations must be unique");
417
+ function parsePluginManifest(value) {
418
+ checkMessageSize(value, 65536);
419
+ return parseOrThrow(manifest, value);
420
+ }
421
+ const envelope = {
422
+ type: z.literal("request"),
423
+ id: z.number().int().positive(),
424
+ contextId: id
425
+ };
426
+ const request = z.discriminatedUnion("method", [
427
+ z.strictObject({
428
+ ...envelope,
429
+ method: z.literal("store.applyOperations"),
430
+ params: z.strictObject({
431
+ operations: z.array(operation).max(5e4),
432
+ options: options.optional()
433
+ })
434
+ }),
435
+ z.strictObject({
436
+ ...envelope,
437
+ method: z.literal("store.refresh"),
438
+ params: z.strictObject({})
439
+ }),
440
+ z.strictObject({
441
+ ...envelope,
442
+ method: z.literal("notifications.notify"),
443
+ params: z.strictObject({
444
+ tone: z.enum(["info", "warning"]),
445
+ title: localizedText(256),
446
+ description: localizedText(4096).optional()
447
+ })
448
+ }),
449
+ z.strictObject({
450
+ ...envelope,
451
+ method: z.literal("files.open"),
452
+ params: fileOpenOptions
453
+ }),
454
+ z.strictObject({
455
+ ...envelope,
456
+ method: z.literal("files.save"),
457
+ params: fileSaveOptions
458
+ })
459
+ ]);
460
+ const wireError = z.strictObject({
461
+ code: z.enum([
462
+ "invalid-input",
463
+ "denied",
464
+ "stale-state",
465
+ "stale-context",
466
+ "unavailable",
467
+ "cancelled",
468
+ "timeout",
469
+ "closed",
470
+ "failed"
471
+ ]),
472
+ issues: z.array(z.strictObject({
473
+ path: text(256),
474
+ message: text(2048)
475
+ })).min(1).max(32),
476
+ displayMessage: localizedText(2048).optional()
477
+ });
478
+ const message = z.union([
479
+ request,
480
+ z.strictObject({
481
+ type: z.literal("contribution"),
482
+ value: z.unknown()
483
+ }),
484
+ z.strictObject({
485
+ type: z.literal("close"),
486
+ reason: z.string().max(2048)
487
+ }),
488
+ z.strictObject({
489
+ type: z.literal("complete"),
490
+ ok: z.literal(true)
491
+ }),
492
+ z.strictObject({
493
+ type: z.literal("complete"),
494
+ ok: z.literal(false),
495
+ error: wireError
496
+ })
497
+ ]);
498
+ const actionDescriptor = z.strictObject({
499
+ id: z.string().max(64).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
500
+ label: localizedText(128),
501
+ supportsViews: z.boolean()
502
+ });
503
+ const actionDescriptors = z.array(actionDescriptor).min(1).max(64).refine((value) => new Set(value.map(({ id }) => id)).size === value.length, "Action IDs must be unique");
504
+ function parseContribution(kind, value) {
505
+ checkMessageSize(value, 1048576);
506
+ if (kind === "theme" || kind === "vocab") return parseDefinition(kind, value);
507
+ return parseOrThrow(actionDescriptors, value);
508
+ }
509
+ const graph = z.strictObject({
510
+ concepts: z.array(z.strictObject({
511
+ id,
512
+ label: z.string(),
513
+ description: z.string().optional(),
514
+ color: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),
515
+ position
516
+ })),
517
+ relationTypes: z.array(relationType),
518
+ relations: z.array(z.strictObject({
519
+ source: id,
520
+ predicate: id,
521
+ target: id
522
+ }))
523
+ });
524
+ const baseStateSchema = z.strictObject({
525
+ revision: z.number().int().nonnegative(),
526
+ contextId: id,
527
+ locale,
528
+ theme: z.strictObject(Object.fromEntries(themeTokens.map((token) => [token, z.string().max(512).regex(/^[#\w\s.,()%/"'-]*$/)]))),
529
+ conceptPlacementOffset: position
530
+ });
531
+ const viewStateSchema = baseStateSchema.extend({
532
+ viewGraph: graph,
533
+ selected: selection,
534
+ targetViewId: id.nullable(),
535
+ activeVocab: z.strictObject({
536
+ id,
537
+ relationTypes: z.array(relationType),
538
+ defaultTypeId: id
539
+ }).nullable(),
540
+ history: z.strictObject({
541
+ canUndo: z.boolean(),
542
+ canRedo: z.boolean()
543
+ }),
544
+ workspace: z.strictObject({
545
+ activeViewId: id.nullable(),
546
+ savedViews: z.array(z.strictObject({
547
+ id,
548
+ name: z.string(),
549
+ pinned: z.boolean(),
550
+ conceptIds: z.array(id).optional()
551
+ }))
552
+ })
553
+ });
554
+ const replies = (state) => z.union([
555
+ z.strictObject({
556
+ type: z.literal("state"),
557
+ state
558
+ }),
559
+ z.strictObject({
560
+ type: z.literal("response"),
561
+ id: z.number().int().positive(),
562
+ ok: z.literal(true),
563
+ value: z.unknown()
564
+ }),
565
+ z.strictObject({
566
+ type: z.literal("response"),
567
+ id: z.number().int().positive(),
568
+ ok: z.literal(false),
569
+ error: wireError
570
+ }),
571
+ z.strictObject({
572
+ type: z.literal("invoke"),
573
+ actionId: id,
574
+ invocation: z.strictObject({ viewId: id.nullable() })
575
+ }),
576
+ z.strictObject({
577
+ type: z.literal("close"),
578
+ reason: z.string().max(2048)
579
+ })
580
+ ]);
581
+ const results = {
582
+ "store.applyOperations": z.strictObject({
583
+ revision: z.number().int().nonnegative(),
584
+ changed: z.boolean()
585
+ }),
586
+ "store.refresh": z.null(),
587
+ "notifications.notify": id,
588
+ "files.open": fileOpenResult,
589
+ "files.save": z.strictObject({ saved: z.boolean() })
590
+ };
591
+ function parsePluginMessage(value) {
592
+ checkMessageSize(value, runtimeLimits.request);
593
+ return parseOrThrow(message, value);
594
+ }
595
+ async function sha256Hex(bytes) {
596
+ const digest = await crypto.subtle.digest("SHA-256", new Uint8Array(bytes));
597
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
598
+ }
599
+ function checkMessageSize(value, limit) {
600
+ const visit = (value, depth) => {
601
+ if (depth > 32) throw new PluginError("invalid-input", [{
602
+ path: "message",
603
+ message: "Nesting limit exceeded"
604
+ }]);
605
+ if (value === null) return;
606
+ if (typeof value === "object") {
607
+ if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype) throw new PluginError("invalid-input", [{
608
+ path: "message",
609
+ message: "Expected plain data"
610
+ }]);
611
+ for (const item of Object.values(value)) visit(item, depth + 1);
612
+ } else if (![
613
+ "string",
614
+ "number",
615
+ "boolean",
616
+ "undefined"
617
+ ].includes(typeof value)) throw new PluginError("invalid-input", [{
618
+ path: "message",
619
+ message: "Expected serializable data"
620
+ }]);
621
+ };
622
+ visit(value, 0);
623
+ if (new TextEncoder().encode(JSON.stringify(value)).byteLength > limit) throw new PluginError("invalid-input", [{
624
+ path: "message",
625
+ message: "Message limit exceeded"
626
+ }]);
627
+ }
628
+ function createPluginClient(port, initial) {
629
+ const schema = "viewGraph" in initial ? viewStateSchema : baseStateSchema;
630
+ const reply = replies(schema);
631
+ let state = parseOrThrow(schema, initial);
632
+ let sequence = 0;
633
+ const listeners = /* @__PURE__ */ new Set();
634
+ const controller = new AbortController();
635
+ const pending = /* @__PURE__ */ new Map();
636
+ const close = () => {
637
+ if (controller.signal.aborted) return;
638
+ controller.abort();
639
+ for (const request of pending.values()) {
640
+ clearTimeout(request.timer);
641
+ request.reject(new PluginError("closed", [{
642
+ path: "channel",
643
+ message: "Plugin channel closed; pending effects may already have completed"
644
+ }]));
645
+ }
646
+ pending.clear();
647
+ listeners.clear();
648
+ port.postMessage({
649
+ type: "close",
650
+ reason: "Plugin client closed"
651
+ });
652
+ port.close();
653
+ };
654
+ const call = async (method, params) => {
655
+ if (controller.signal.aborted) return Promise.reject(new PluginError("closed", [{
656
+ path: "channel",
657
+ message: "Plugin channel closed"
658
+ }]));
659
+ if (pending.size >= runtimeLimits.pending) return Promise.reject(new PluginError("failed", [{
660
+ path: "channel",
661
+ message: "Too many pending requests"
662
+ }]));
663
+ const id = ++sequence;
664
+ const value = {
665
+ type: "request",
666
+ id,
667
+ contextId: state.contextId,
668
+ method,
669
+ params
670
+ };
671
+ parsePluginMessage(value);
672
+ return new Promise((resolve, reject) => {
673
+ const timer = setTimeout(close, method.startsWith("files.") ? runtimeLimits.interaction : runtimeLimits.deadline);
674
+ pending.set(id, {
675
+ method,
676
+ resolve: (value) => resolve(value),
677
+ reject,
678
+ timer
679
+ });
680
+ port.postMessage(value);
681
+ });
682
+ };
683
+ port.onmessage = ({ data: value, ports }) => {
684
+ if (controller.signal.aborted) return;
685
+ if (ports.length) {
686
+ close();
687
+ return;
688
+ }
689
+ const parsed = reply.safeParse(value);
690
+ if (!parsed.success) {
691
+ console.error(new PluginError("invalid-input", parsed.error.issues.map((issue) => ({
692
+ path: issue.path.join("."),
693
+ message: issue.message
694
+ }))).message);
695
+ close();
696
+ return;
697
+ }
698
+ const data = parsed.data;
699
+ if (data.type === "close") {
700
+ close();
701
+ return;
702
+ }
703
+ if (data.type === "state" && data.state.revision > state.revision) {
704
+ state = data.state;
705
+ for (const listener of listeners) try {
706
+ listener();
707
+ } catch {
708
+ console.error(new PluginError("failed", [{
709
+ path: "subscriber",
710
+ message: "Plugin state subscriber failed"
711
+ }]));
712
+ }
713
+ }
714
+ if (data.type !== "response") return;
715
+ const request = pending.get(data.id);
716
+ if (!request) return;
717
+ if (data.ok && !results[request.method].safeParse(data.value).success) {
718
+ close();
719
+ return;
720
+ }
721
+ pending.delete(data.id);
722
+ clearTimeout(request.timer);
723
+ if (data.ok) request.resolve(data.value);
724
+ else request.reject(new PluginError(data.error.code, data.error.issues, data.error.displayMessage));
725
+ };
726
+ port.onmessageerror = close;
727
+ port.start();
728
+ const applyOperations = (operations, options) => call("store.applyOperations", {
729
+ operations,
730
+ ...options ? { options } : {}
731
+ });
732
+ const { undo: _undo, redo: _redo, setView: _view, setActiveVocab: _vocab, setActiveTheme: _theme, setLocale: _locale, setPanelSizes: _panels, setSectionOpen: _section, createView: _createView, renameView: _renameView, setViewPinned: _pin, deleteView: _deleteView, ...writes } = createWriteCommands(async (operations, options) => {
733
+ await applyOperations(operations, options);
734
+ }, async (id, committed) => {
735
+ await committed;
736
+ return id;
737
+ });
738
+ return {
739
+ context: {
740
+ store: {
741
+ ...writes,
742
+ getState: () => state,
743
+ subscribe: (listener) => {
744
+ listeners.add(listener);
745
+ return () => listeners.delete(listener);
746
+ },
747
+ refresh: async () => {
748
+ await call("store.refresh", {});
749
+ return state;
750
+ },
751
+ applyOperations
752
+ },
753
+ notifications: { notify: (value) => call("notifications.notify", value) },
754
+ files: {
755
+ open: (options) => call("files.open", options),
756
+ save: (options) => call("files.save", options)
757
+ },
758
+ signal: controller.signal
759
+ },
760
+ close
761
+ };
762
+ }
763
+ //#endregion
764
+ export { parsePluginManifest as a, sha256Hex as c, fileTextLimit as d, parseFileOptions as f, parsePluginI18n as i, themeTokens as l, themeColors as m, createPluginClient as n, parsePluginMessage as o, parseDefinition as p, parseContribution as r, runtimeLimits as s, checkMessageSize as t, resolvePluginText as u };