@plugmatica/plugin-sdk 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.
package/dist/index.js ADDED
@@ -0,0 +1,749 @@
1
+ import { usePluginNavigation } from './chunk-ACHELRPS.js';
2
+ export { PluginMessage, PluginRuntimeProvider, assertExternalNavigationUrl, createPluginRuntime, usePluginApi, usePluginContext, usePluginExtensions, usePluginGuestSession, usePluginI18n, usePluginManagedResources, usePluginNavigation, usePluginSession, usePluginWorkflowRealtime, usePluginWorkflows } from './chunk-ACHELRPS.js';
3
+ import { extensionTarget } from './chunk-YY4H56JF.js';
4
+ export { defineActions, defineEventHandler, defineExtension, defineOperationHook, defineProvider, defineRepeatedInstances, extensionTarget } from './chunk-YY4H56JF.js';
5
+ export { declareMessages } from '@plugmatica/i18n';
6
+ import * as React from 'react';
7
+ import { createElement, lazy, Suspense } from 'react';
8
+
9
+ // src/entities.ts
10
+ var DEFAULT_UPLOAD_CHUNK_BYTES = 8 * 1024 * 1024;
11
+ function ownerEntity(api, entity) {
12
+ const base = `/_entities/${segment(entity)}`;
13
+ const importsBase = `${base}/_imports`;
14
+ const exportsBase = `${base}/_exports`;
15
+ return {
16
+ reference: (field) => ownerEntityReference(api, base, field),
17
+ schema: (requestOptions) => api.get(`${base}/_schema`, requestOptions),
18
+ list: (options, requestOptions) => api.get(
19
+ `${base}${pageQuery(options)}`,
20
+ requestOptions
21
+ ),
22
+ get: (pid, requestOptions) => api.get(`${base}/${segment(pid)}`, requestOptions),
23
+ create: (value) => api.post(base, { value }),
24
+ update: (pid, update) => api.patch(`${base}/${segment(pid)}`, update),
25
+ delete: (pid, expectedRevision) => {
26
+ const query = new URLSearchParams({
27
+ expectedRevision: String(expectedRevision)
28
+ });
29
+ return api.delete(
30
+ `${base}/${segment(pid)}?${query.toString()}`
31
+ );
32
+ },
33
+ bulkWrite: (request) => api.post(`${base}/_bulk`, request),
34
+ createImport: (request) => api.post(importsBase, request),
35
+ uploadImport: (pid, source, options) => uploadImportSource(
36
+ api,
37
+ `${importsBase}/${segment(pid)}/content`,
38
+ source,
39
+ options
40
+ ),
41
+ getImport: (pid) => api.get(`${importsBase}/${segment(pid)}`),
42
+ previewImport: (pid, options) => api.get(
43
+ `${importsBase}/${segment(pid)}/preview${previewQuery(options)}`
44
+ ),
45
+ validateImport: (pid) => api.post(`${importsBase}/${segment(pid)}/validate`),
46
+ commitImport: (pid) => api.post(`${importsBase}/${segment(pid)}/commit`),
47
+ cancelImport: (pid) => api.post(`${importsBase}/${segment(pid)}/cancel`),
48
+ downloadImportErrors: (pid) => api.getBlob(`${importsBase}/${segment(pid)}/errors`),
49
+ createExport: (request) => api.post(exportsBase, request),
50
+ getExport: (pid) => api.get(`${exportsBase}/${segment(pid)}`),
51
+ cancelExport: (pid) => api.post(`${exportsBase}/${segment(pid)}/cancel`),
52
+ downloadExport: (pid) => api.getBlob(`${exportsBase}/${segment(pid)}/content`)
53
+ };
54
+ }
55
+ function dependencyEntity(api, plugin, entity) {
56
+ const base = `/_dependencies/${segment(plugin)}/entities/${segment(entity)}`;
57
+ return {
58
+ schema: (requestOptions) => api.get(`${base}/_schema`, requestOptions),
59
+ list: (options, requestOptions) => api.get(
60
+ `${base}${pageQuery(options)}`,
61
+ requestOptions
62
+ ),
63
+ get: (pid, requestOptions) => api.get(`${base}/${segment(pid)}`, requestOptions)
64
+ };
65
+ }
66
+ function ownerEntityReference(api, ownerBase, field) {
67
+ const base = `${ownerBase}/_references/${segment(field)}`;
68
+ return {
69
+ search: (options, requestOptions) => api.get(
70
+ `${base}${referenceSearchQuery(options)}`,
71
+ requestOptions
72
+ ),
73
+ resolve: (pid, requestOptions) => api.get(`${base}/${segment(pid)}`, requestOptions),
74
+ resolveMany: (pids, requestOptions) => api.post(
75
+ `${base}/_resolve`,
76
+ { pids: [...pids] },
77
+ requestOptions
78
+ ).then((response) => response.items)
79
+ };
80
+ }
81
+ function referenceSearchQuery(options) {
82
+ if (!options) return "";
83
+ const query = new URLSearchParams();
84
+ const text = options.text?.trim();
85
+ if (text) query.set("q", text);
86
+ if (options.limit != null) query.set("limit", String(options.limit));
87
+ if (options.cursor) query.set("cursor", options.cursor);
88
+ const encoded = query.toString();
89
+ return encoded ? `?${encoded}` : "";
90
+ }
91
+ async function uploadImportSource(api, path, source, options) {
92
+ if (source.size <= 0) {
93
+ throw new Error("Import source cannot be empty.");
94
+ }
95
+ const chunkBytes = options?.chunkBytes ?? DEFAULT_UPLOAD_CHUNK_BYTES;
96
+ if (!Number.isSafeInteger(chunkBytes) || chunkBytes <= 0) {
97
+ throw new Error("Import upload chunkBytes must be a positive integer.");
98
+ }
99
+ const sourceName = options?.fileName ?? blobName(source);
100
+ let offset = 0;
101
+ let job = null;
102
+ while (offset < source.size) {
103
+ if (options?.signal?.aborted) {
104
+ throw abortError();
105
+ }
106
+ const endExclusive = Math.min(offset + chunkBytes, source.size);
107
+ const chunk = source.slice(offset, endExclusive, source.type);
108
+ const headers = new Headers();
109
+ headers.set(
110
+ "Content-Range",
111
+ `bytes ${offset}-${endExclusive - 1}/${source.size}`
112
+ );
113
+ headers.set("Content-Type", source.type || "application/octet-stream");
114
+ if (sourceName) {
115
+ headers.set("X-Upload-Filename", encodeURIComponent(sourceName));
116
+ }
117
+ const requestOptions = {
118
+ headers,
119
+ signal: options?.signal
120
+ };
121
+ job = await api.put(path, chunk, requestOptions);
122
+ offset = endExclusive;
123
+ options?.onProgress?.({
124
+ uploadedBytes: offset,
125
+ totalBytes: source.size,
126
+ fraction: offset / source.size
127
+ });
128
+ }
129
+ if (!job) {
130
+ throw new Error("Import upload completed without a job response.");
131
+ }
132
+ return job;
133
+ }
134
+ function blobName(source) {
135
+ if (typeof File !== "undefined" && source instanceof File) {
136
+ return source.name;
137
+ }
138
+ return void 0;
139
+ }
140
+ function abortError() {
141
+ if (typeof DOMException !== "undefined") {
142
+ return new DOMException("Import upload aborted.", "AbortError");
143
+ }
144
+ return new Error("Import upload aborted.");
145
+ }
146
+ function pageQuery(options) {
147
+ const query = new URLSearchParams();
148
+ if (options?.limit != null) {
149
+ query.set("limit", String(options.limit));
150
+ }
151
+ if (options?.cursor != null && String(options.cursor).trim()) {
152
+ query.set("cursor", String(options.cursor));
153
+ }
154
+ const encoded = query.toString();
155
+ return encoded ? `?${encoded}` : "";
156
+ }
157
+ function previewQuery(options) {
158
+ const query = new URLSearchParams();
159
+ if (options?.offset != null) {
160
+ query.set("offset", String(options.offset));
161
+ }
162
+ if (options?.limit != null) {
163
+ query.set("limit", String(options.limit));
164
+ }
165
+ const encoded = query.toString();
166
+ return encoded ? `?${encoded}` : "";
167
+ }
168
+ function segment(value) {
169
+ const trimmed = value.trim();
170
+ if (!trimmed) {
171
+ throw new Error("Plugin entity path segment cannot be empty.");
172
+ }
173
+ return encodeURIComponent(trimmed);
174
+ }
175
+ function matchPluginRoute(pattern, path) {
176
+ const patternSegments = segments(normalizePluginPattern(pattern));
177
+ const pathSegments = segments(normalizePluginPath(path));
178
+ const params = {};
179
+ let pathIndex = 0;
180
+ for (let patternIndex = 0; patternIndex < patternSegments.length; patternIndex += 1) {
181
+ const segment2 = patternSegments[patternIndex];
182
+ if (!segment2.startsWith(":")) {
183
+ const value2 = pathSegments[pathIndex];
184
+ if (value2 == null || decodeSegment(value2) !== segment2) return null;
185
+ pathIndex += 1;
186
+ continue;
187
+ }
188
+ const raw = segment2.slice(1);
189
+ const catchAll = raw.endsWith("*");
190
+ const optional = raw.endsWith("?");
191
+ const name = raw.replace(/[?*]$/, "");
192
+ if (!name)
193
+ throw new Error(`Invalid Plugmatica route pattern '${pattern}'.`);
194
+ if (catchAll) {
195
+ if (patternIndex !== patternSegments.length - 1) {
196
+ throw new Error(
197
+ `Catch-all route parameter ':${raw}' must be the final segment.`
198
+ );
199
+ }
200
+ setRouteParam(
201
+ params,
202
+ name,
203
+ pathSegments.slice(pathIndex).map(decodeSegment).join("/")
204
+ );
205
+ pathIndex = pathSegments.length;
206
+ break;
207
+ }
208
+ const value = pathSegments[pathIndex];
209
+ if (value == null) {
210
+ if (optional && patternIndex === patternSegments.length - 1) continue;
211
+ return null;
212
+ }
213
+ setRouteParam(params, name, decodeSegment(value));
214
+ pathIndex += 1;
215
+ }
216
+ if (pathIndex !== pathSegments.length) return null;
217
+ return params;
218
+ }
219
+ function usePluginCurrentPath() {
220
+ const navigation = usePluginNavigation();
221
+ const subscribe = React.useCallback(
222
+ (listener) => navigation.subscribe?.(listener) ?? noopSubscribe(),
223
+ [navigation]
224
+ );
225
+ const snapshot = React.useCallback(() => navigation.currentPath(), [navigation]);
226
+ return React.useSyncExternalStore(subscribe, snapshot, snapshot);
227
+ }
228
+ function usePluginRouteMatch(pattern) {
229
+ return matchPluginRoute(pattern, usePluginCurrentPath());
230
+ }
231
+ function normalizePluginPath(value) {
232
+ const withoutHash = value.split("#", 1)[0] ?? "";
233
+ const withoutQuery = withoutHash.split("?", 1)[0] ?? "";
234
+ const withLeadingSlash = withoutQuery.startsWith("/") ? withoutQuery : `/${withoutQuery}`;
235
+ const collapsed = withLeadingSlash.replace(/\/{2,}/g, "/");
236
+ return collapsed.length > 1 ? collapsed.replace(/\/+$/, "") : "/";
237
+ }
238
+ function normalizePluginPattern(value) {
239
+ const trimmed = value.trim();
240
+ const withLeadingSlash = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
241
+ const collapsed = withLeadingSlash.replace(/\/{2,}/g, "/");
242
+ return collapsed.length > 1 ? collapsed.replace(/\/+$/, "") : "/";
243
+ }
244
+ function segments(value) {
245
+ return value === "/" ? [] : value.slice(1).split("/");
246
+ }
247
+ function setRouteParam(params, name, value) {
248
+ if (name === "__proto__") {
249
+ Object.defineProperty(params, name, {
250
+ value,
251
+ enumerable: true,
252
+ configurable: true,
253
+ writable: true
254
+ });
255
+ } else {
256
+ params[name] = value;
257
+ }
258
+ }
259
+ function decodeSegment(value) {
260
+ try {
261
+ return decodeURIComponent(value);
262
+ } catch (error) {
263
+ throw new Error(
264
+ `Invalid percent-encoding in plugin route segment '${value}'.`,
265
+ {
266
+ cause: error
267
+ }
268
+ );
269
+ }
270
+ }
271
+ function noopSubscribe() {
272
+ return () => void 0;
273
+ }
274
+
275
+ // src/workflowNodes.ts
276
+ var WORKFLOW_NODE_UI_CONTRACT = "plugmatica.workflow.node.host";
277
+ var WORKFLOW_NODE_UI_SURFACE = "workflow.node";
278
+ var workflowNodeUiTargets = {
279
+ catalog: extensionTarget.ui({
280
+ surface: "custom",
281
+ key: WORKFLOW_NODE_UI_SURFACE,
282
+ point: "catalog",
283
+ required: false,
284
+ contract: { id: WORKFLOW_NODE_UI_CONTRACT, version: "^1.1.0" }
285
+ }),
286
+ editor: extensionTarget.ui({
287
+ surface: "custom",
288
+ key: WORKFLOW_NODE_UI_SURFACE,
289
+ point: "editor",
290
+ required: false,
291
+ contract: { id: WORKFLOW_NODE_UI_CONTRACT, version: "^1.0.0" }
292
+ }),
293
+ presentation: extensionTarget.ui({
294
+ surface: "custom",
295
+ key: WORKFLOW_NODE_UI_SURFACE,
296
+ point: "presentation",
297
+ required: false,
298
+ contract: { id: WORKFLOW_NODE_UI_CONTRACT, version: "^1.0.0" }
299
+ })
300
+ };
301
+
302
+ // src/workflowNodeFacet.ts
303
+ function workflowNodeFacetAccepts(point, payload, nodeType, available) {
304
+ if (point === "catalog") {
305
+ return available.catalog && Array.isArray(payload?.nodeTypes) && payload.nodeTypes.includes(nodeType);
306
+ }
307
+ if (payload?.nodeType !== nodeType) return false;
308
+ if (point === "editor") return available.editor;
309
+ if (point === "presentation") return available.presentation;
310
+ return false;
311
+ }
312
+
313
+ // src/defineWorkflowNode.ts
314
+ function defineWorkflowNode(definition) {
315
+ if (definition.editor && definition.loadEditor) {
316
+ throw new Error(
317
+ `Workflow node '${definition.nodeType}' cannot declare both editor and loadEditor.`
318
+ );
319
+ }
320
+ if (definition.presentation && definition.loadPresentation) {
321
+ throw new Error(
322
+ `Workflow node '${definition.nodeType}' cannot declare both presentation and loadPresentation.`
323
+ );
324
+ }
325
+ const editor = view(definition.editor, definition.loadEditor);
326
+ const presentation = view(
327
+ definition.presentation,
328
+ definition.loadPresentation
329
+ );
330
+ const key = definition.nodeType;
331
+ const availability = {
332
+ catalog: Boolean(definition.catalog),
333
+ editor: Boolean(editor),
334
+ presentation: Boolean(presentation)
335
+ };
336
+ const accepts = (point, payload) => workflowNodeFacetAccepts(point, payload, key, availability);
337
+ return {
338
+ visible: ({ point, payload }) => accepts(point, payload),
339
+ contribute: ({ point, payload, t }) => {
340
+ if (!accepts(point, payload)) {
341
+ throw new Error(
342
+ `Workflow node '${key}' cannot contribute to '${point}'.`
343
+ );
344
+ }
345
+ switch (point) {
346
+ case "catalog": {
347
+ const catalog = definition.catalog;
348
+ return {
349
+ key: `${key}.catalog`,
350
+ nodeType: key,
351
+ title: t(catalog.titleKey),
352
+ ...catalog.descriptionKey ? { description: t(catalog.descriptionKey) } : {},
353
+ ...catalog.categoryKey ? { category: t(catalog.categoryKey) } : {},
354
+ ...catalog.icon ? { icon: catalog.icon } : {},
355
+ ...catalog.keywords ? { keywords: [...catalog.keywords] } : {}
356
+ };
357
+ }
358
+ case "editor":
359
+ return {
360
+ key: `${key}.editor`,
361
+ nodeType: key,
362
+ order: definition.order ?? 1e3,
363
+ render: (context) => editor({ ...context, translate: (messageKey) => t(messageKey) })
364
+ };
365
+ case "presentation":
366
+ return {
367
+ key: `${key}.presentation`,
368
+ nodeType: key,
369
+ order: definition.order ?? 1e3,
370
+ render: (context) => presentation({
371
+ ...context,
372
+ translate: (messageKey) => t(messageKey)
373
+ })
374
+ };
375
+ default:
376
+ throw new Error(
377
+ `Workflow node '${key}' requires a supported host point.`
378
+ );
379
+ }
380
+ }
381
+ };
382
+ }
383
+ function view(component, loader) {
384
+ if (component) return (props) => createElement(component, props);
385
+ if (!loader) return void 0;
386
+ const Lazy = lazy(loader);
387
+ return (props) => createElement(Suspense, { fallback: null }, createElement(Lazy, props));
388
+ }
389
+
390
+ // src/workflowNodeFields.ts
391
+ var DEFAULT_WORKFLOW_FIELD_LABELS = {
392
+ choose: "Choose a value",
393
+ recommended: "Recommended matching data",
394
+ fixed: "Fixed value",
395
+ formula: "Formula / expression",
396
+ clear: "Clear value",
397
+ search: "Search available values",
398
+ required: "Required",
399
+ optional: "May be unavailable",
400
+ conditional: "Available on some paths",
401
+ unverified: "This saved source is not available to this step. Check the upstream node and its connection, then choose an available value.",
402
+ empty: "No compatible values",
403
+ trueLabel: "True",
404
+ falseLabel: "False"
405
+ };
406
+ var UNSAFE_SEGMENTS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
407
+ var MAX_PATH_DEPTH = 12;
408
+ var MAX_LITERAL_BYTES = 64 * 1024;
409
+ function immutableJson(value) {
410
+ if (value === void 0 || value === null || typeof value !== "object") return value;
411
+ const clone = structuredClone(value);
412
+ const visit = (item) => {
413
+ if (item === null || typeof item !== "object" || Object.isFrozen(item)) return;
414
+ Object.freeze(item);
415
+ for (const child of Object.values(item)) visit(child);
416
+ };
417
+ visit(clone);
418
+ return clone;
419
+ }
420
+ function record(value) {
421
+ return value !== null && typeof value === "object" && !Array.isArray(value);
422
+ }
423
+ function segments2(path) {
424
+ if (typeof path !== "string" || path.length > 512) return null;
425
+ const items = path.split(".");
426
+ return items.length > 0 && items.length <= MAX_PATH_DEPTH && items.every((item) => item.length > 0 && item.length <= 128 && !UNSAFE_SEGMENTS.has(item) && !item.includes("[") && !item.includes("]")) ? items : null;
427
+ }
428
+ function forbidden(schema) {
429
+ return schema.readOnly === true || schema.writeOnly === true || schema["x-sensitive"] === true || schema["x-plugmatica-sensitive"] === true || schema["x-plugmatica-secret"] === true || schema["x-plugmatica-hidden"] === true || schema["x-plugmatica-ui"] === "hidden" || schema["x-plugmatica-generated"] !== void 0 && schema["x-plugmatica-generated"] !== false || Object.hasOwn(schema, "const");
430
+ }
431
+ function fieldAt(schema, parts) {
432
+ let current = record(schema) ? schema : null;
433
+ if (!current || forbidden(current)) return void 0;
434
+ for (const part of parts) {
435
+ const properties = record(current.properties) ? current.properties : null;
436
+ if (!properties || !Object.hasOwn(properties, part)) return void 0;
437
+ const child = properties[part];
438
+ if (!record(child) || forbidden(child)) return void 0;
439
+ current = child;
440
+ }
441
+ return current;
442
+ }
443
+ function pathIsResource(path, descriptor) {
444
+ return (descriptor.resourceBindings ?? []).some((binding) => path === binding.configPath || path.startsWith(`${binding.configPath}.`) || binding.configPath.startsWith(`${path}.`));
445
+ }
446
+ function valueAt(root, parts) {
447
+ let current = root;
448
+ for (const part of parts) {
449
+ if (!record(current) || !Object.hasOwn(current, part)) return void 0;
450
+ current = current[part];
451
+ }
452
+ return current;
453
+ }
454
+ function updatedValue(root, parts, nextValue, remove) {
455
+ const before = record(root) ? root : {};
456
+ const result = { ...before };
457
+ const part = parts[0];
458
+ if (parts.length === 1) {
459
+ if (remove) delete result[part];
460
+ else result[part] = nextValue;
461
+ } else {
462
+ const child = updatedValue(before[part], parts.slice(1), nextValue, remove);
463
+ if (remove && !Object.keys(child).length) delete result[part];
464
+ else result[part] = child;
465
+ }
466
+ return result;
467
+ }
468
+ function literalExpression(expression) {
469
+ try {
470
+ const parsed = JSON.parse(expression);
471
+ if (parsed === null || typeof parsed === "string" || typeof parsed === "boolean" || typeof parsed === "number" && Number.isFinite(parsed)) {
472
+ return { value: parsed };
473
+ }
474
+ } catch {
475
+ }
476
+ return null;
477
+ }
478
+ function supportsFixed(schema, canUseConfig) {
479
+ if (canUseConfig) return true;
480
+ const types = Array.isArray(schema.type) ? schema.type : [schema.type];
481
+ return types.every((type) => type === void 0 || ["string", "number", "integer", "boolean", "null"].includes(type));
482
+ }
483
+ function typeSupportsValue(schema, value) {
484
+ const types = Array.isArray(schema.type) ? schema.type : schema.type ? [schema.type] : [];
485
+ if (!types.length) return true;
486
+ return types.some((type) => type === "null" && value === null || type === "string" && typeof value === "string" || type === "boolean" && typeof value === "boolean" || type === "number" && typeof value === "number" && Number.isFinite(value) || type === "integer" && typeof value === "number" && Number.isSafeInteger(value) || type === "object" && record(value) || type === "array" && Array.isArray(value));
487
+ }
488
+ function sameValue(a, b) {
489
+ return a === b || JSON.stringify(a) === JSON.stringify(b);
490
+ }
491
+ function workflowFieldHasValue(value) {
492
+ if (value === void 0 || value === null) return false;
493
+ if (typeof value === "string") return value.trim().length > 0;
494
+ if (Array.isArray(value)) return value.length > 0;
495
+ return true;
496
+ }
497
+ function normalizedSemantic(value) {
498
+ if (typeof value !== "string" || value.length > 256) return void 0;
499
+ const trimmed = value.trim().toLowerCase();
500
+ return trimmed || void 0;
501
+ }
502
+ function sourceSemanticRank(target, source) {
503
+ const requested = normalizedSemantic(target);
504
+ const offered = normalizedSemantic(source);
505
+ if (!requested || !offered) return 1;
506
+ return requested === offered ? 0 : 2;
507
+ }
508
+ function isDirectWorkflowDataPath(expression) {
509
+ return /^\$\.(?:trigger|nodes|steps|variables|config)(?:\.[A-Za-z0-9_-]+)*$/.test(expression);
510
+ }
511
+ function visiblePaths(schema, prefix = "", depth = 0) {
512
+ if (depth >= MAX_PATH_DEPTH || !record(schema) || forbidden(schema)) return [];
513
+ const properties = record(schema.properties) ? schema.properties : null;
514
+ if (!properties) return [];
515
+ const result = [];
516
+ for (const [key, field] of Object.entries(properties)) {
517
+ const path = prefix ? `${prefix}.${key}` : key;
518
+ if (!segments2(path) || !record(field) || forbidden(field)) continue;
519
+ const descendants = visiblePaths(field, path, depth + 1);
520
+ if (descendants.length) result.push(...descendants);
521
+ else if (!record(field.properties) || !Object.keys(field.properties).length) result.push(path);
522
+ }
523
+ return result;
524
+ }
525
+ function createWorkflowNodeFields(options) {
526
+ const { node, descriptor, inputSchema, configSchema, sources, issues, readOnly, onChange } = options;
527
+ const inputDefaults = configSchema?.["x-plugmatica-input-defaults"] === true;
528
+ const paths = /* @__PURE__ */ new Map();
529
+ for (const [channel, schema] of [["config", configSchema], ["input", inputSchema]]) {
530
+ const source = record(schema) ? schema : null;
531
+ for (const path of visiblePaths(source)) {
532
+ if (pathIsResource(path, descriptor)) continue;
533
+ const parts = segments2(path);
534
+ const field = parts && fieldAt(source, parts);
535
+ if (!field) continue;
536
+ let required = true;
537
+ let parent = source;
538
+ for (const part of parts) {
539
+ required &&= Array.isArray(parent.required) && parent.required.includes(part);
540
+ parent = record(parent.properties) && record(parent.properties[part]) ? parent.properties[part] : {};
541
+ }
542
+ paths.set(path, { channel, schema: immutableJson(field), required });
543
+ }
544
+ }
545
+ function definition(path) {
546
+ return segments2(path) ? paths.get(path) : void 0;
547
+ }
548
+ function snapshot(path) {
549
+ const def = definition(path);
550
+ if (!def) return void 0;
551
+ const parts = segments2(path);
552
+ const current = options.currentNode();
553
+ const activeNode = current?.id === node.id && current?.type === node.type ? current : node;
554
+ const mappings = activeNode.inputMappings ?? {};
555
+ const expression = def.channel === "input" ? mappings[path]?.expression ?? "" : "";
556
+ const configured = valueAt(activeNode.config, parts);
557
+ const literal = literalExpression(expression);
558
+ const requestedSemantic = def.schema["x-plugmatica-semantic"];
559
+ const allowedSources = def.channel === "input" ? sources.map((candidate) => {
560
+ const semanticRank = sourceSemanticRank(requestedSemantic, candidate.semantic);
561
+ return {
562
+ ...candidate,
563
+ // Conditional branches and optional array/field members are visible,
564
+ // but must never be advertised as a guaranteed one-click match.
565
+ recommended: semanticRank === 0 && candidate.availability === "always" && candidate.presence !== "optional",
566
+ // Never suggest an explicitly different semantic just because both
567
+ // fields share a broad JSON type such as "string".
568
+ compatibility: semanticRank === 2 ? "incompatible" : options.sourceCompatibility?.(def.schema.type, candidate.type) ?? candidate.compatibility
569
+ };
570
+ }).filter((candidate) => candidate.compatibility !== "incompatible").sort((a, b) => Number(b.recommended) - Number(a.recommended)) : [];
571
+ const selectedSource = allowedSources.find((candidate) => candidate.expression === expression.trim());
572
+ const selected = selectedSource !== void 0;
573
+ const useConfigLiteral = def.channel === "config" || inputDefaults;
574
+ const mode = expression.trim() ? selected ? "source" : literal ? "fixed" : "formula" : useConfigLiteral && configured !== void 0 ? "fixed" : "unset";
575
+ const value = mode === "fixed" ? immutableJson(expression.trim() ? literal?.value : configured) : void 0;
576
+ const referenceStatus = selectedSource ? selectedSource.availability === "conditional" ? "conditional" : selectedSource.presence === "optional" ? "optional" : "available" : mode === "formula" && isDirectWorkflowDataPath(expression.trim()) ? "unverified" : void 0;
577
+ const fieldIssues = issues.filter((issue) => issue.field === `config.${path}` || issue.field === `inputMappings.${path}`).map((issue) => immutableJson(issue));
578
+ return {
579
+ path,
580
+ schema: def.schema,
581
+ label: typeof def.schema.title === "string" && def.schema.title.trim() ? def.schema.title.trim() : path,
582
+ required: def.required,
583
+ channel: def.channel,
584
+ supportsFixed: supportsFixed(def.schema, useConfigLiteral),
585
+ supportsExpression: def.channel === "input",
586
+ mode,
587
+ configured: mode === "fixed" ? workflowFieldHasValue(value) : mode !== "unset" && referenceStatus !== "unverified",
588
+ referenceStatus,
589
+ value,
590
+ expression,
591
+ sources: allowedSources.map((source) => immutableJson(source)),
592
+ issues: fieldIssues
593
+ };
594
+ }
595
+ function commit(path, mode, value) {
596
+ const def = definition(path);
597
+ if (!def) throw new Error(`Workflow field '${path}' is not an editable input or configuration path`);
598
+ if (readOnly || !options.isActive()) return;
599
+ const current = options.currentNode();
600
+ if (!current || current.id !== node.id || current.type !== node.type) return;
601
+ const parts = segments2(path);
602
+ const configured = valueAt(current.config, parts);
603
+ const mappings = current.inputMappings ?? {};
604
+ const oldExpression = mappings[path]?.expression;
605
+ const nextMappings = { ...mappings };
606
+ let configChanged = false;
607
+ let mappingsChanged = false;
608
+ let nextConfig;
609
+ if (mode === "literal") {
610
+ if (!supportsFixed(def.schema, def.channel === "config" || inputDefaults)) {
611
+ throw new Error(`Workflow field '${path}' does not allow fixed values`);
612
+ }
613
+ if (!typeSupportsValue(def.schema, value)) throw new Error(`Invalid value type for Workflow field '${path}'`);
614
+ let encoded;
615
+ try {
616
+ encoded = JSON.stringify(value);
617
+ if (typeof encoded !== "string" || encoded.length > MAX_LITERAL_BYTES) throw new Error("invalid");
618
+ } catch {
619
+ throw new Error(`Workflow field '${path}' requires a bounded JSON value`);
620
+ }
621
+ if (def.channel === "config" || inputDefaults) {
622
+ if (!sameValue(configured, value)) {
623
+ nextConfig = updatedValue(current.config, parts, JSON.parse(encoded), false);
624
+ configChanged = true;
625
+ }
626
+ } else {
627
+ if (configured !== void 0) {
628
+ nextConfig = updatedValue(current.config, parts, void 0, true);
629
+ configChanged = true;
630
+ }
631
+ if (oldExpression !== encoded) {
632
+ nextMappings[path] = { expression: encoded };
633
+ mappingsChanged = true;
634
+ }
635
+ }
636
+ if ((def.channel === "config" || inputDefaults) && oldExpression !== void 0) {
637
+ delete nextMappings[path];
638
+ mappingsChanged = true;
639
+ }
640
+ } else {
641
+ if (mode === "mapping") {
642
+ if (def.channel !== "input") throw new Error(`Workflow config field '${path}' cannot be mapped`);
643
+ if (typeof value !== "string" || value.length > 32768) throw new Error("Invalid Workflow expression");
644
+ const expression = value.trim();
645
+ if (expression) {
646
+ const source = sources.find((candidate) => candidate.expression === expression);
647
+ if (source && (sourceSemanticRank(def.schema["x-plugmatica-semantic"], source.semantic) === 2 || (options.sourceCompatibility?.(def.schema.type, source.type) ?? source.compatibility) === "incompatible")) {
648
+ throw new Error(`Incompatible Workflow mapping source for '${path}'`);
649
+ }
650
+ if (oldExpression !== value) {
651
+ nextMappings[path] = { expression: value };
652
+ mappingsChanged = true;
653
+ }
654
+ } else if (oldExpression !== void 0) {
655
+ delete nextMappings[path];
656
+ mappingsChanged = true;
657
+ }
658
+ } else if (oldExpression !== void 0) {
659
+ delete nextMappings[path];
660
+ mappingsChanged = true;
661
+ }
662
+ if (configured !== void 0 && (mode === "clear" || def.channel === "input")) {
663
+ nextConfig = updatedValue(current.config, parts, void 0, true);
664
+ configChanged = true;
665
+ }
666
+ }
667
+ if (!configChanged && !mappingsChanged) return;
668
+ onChange({ ...configChanged ? { config: nextConfig } : {}, ...mappingsChanged ? { inputMappings: nextMappings } : {} });
669
+ }
670
+ return {
671
+ nodeId: node.id,
672
+ readOnly,
673
+ labels: options.labels ?? DEFAULT_WORKFLOW_FIELD_LABELS,
674
+ list: () => [...paths.keys()].map(snapshot).filter((item) => item !== void 0),
675
+ get: snapshot,
676
+ setLiteral: (path, value) => commit(path, "literal", value),
677
+ setMapping: (path, expression) => commit(path, "mapping", expression),
678
+ clear: (path) => commit(path, "clear"),
679
+ registerAnchor(path, element) {
680
+ const def = definition(path);
681
+ if (!def) return;
682
+ if (def.channel === "input") {
683
+ options.onRegisterAnchor?.(`inputMappings.${path}`, element);
684
+ if (inputDefaults) options.onRegisterAnchor?.(`config.${path}`, element);
685
+ } else {
686
+ options.onRegisterAnchor?.(`config.${path}`, element);
687
+ }
688
+ }
689
+ };
690
+ }
691
+ function useWorkflowNodeField(fields, path) {
692
+ return fields.get(path);
693
+ }
694
+ var MAX_PRESENTATION_FIELDS = 24;
695
+ function workflowUpstreamNodeIds(graph, nodeId) {
696
+ const parents = /* @__PURE__ */ new Map();
697
+ const validIds = new Set(graph.nodes.map((node) => node.id));
698
+ for (const edge of graph.edges) {
699
+ if (!validIds.has(edge.source) || !validIds.has(edge.target)) continue;
700
+ if (!parents.has(edge.target)) parents.set(edge.target, []);
701
+ parents.get(edge.target).push(edge.source);
702
+ }
703
+ const result = /* @__PURE__ */ new Set();
704
+ const queue = [...parents.get(nodeId) ?? []];
705
+ for (let index = 0; index < queue.length; index += 1) {
706
+ const candidate = queue[index];
707
+ if (candidate === nodeId || result.has(candidate)) continue;
708
+ result.add(candidate);
709
+ queue.push(...parents.get(candidate) ?? []);
710
+ }
711
+ return result;
712
+ }
713
+ function directWorkflowNodeSource(expression) {
714
+ return /^\$\.nodes\.([A-Za-z0-9_-]+)\.(?:output|error)(?:\.[A-Za-z0-9_-]+)*$/.exec(expression)?.[1];
715
+ }
716
+ function projectWorkflowNodePresentationFields(node, descriptor, upstreamNodeIds) {
717
+ const schema = record(descriptor.inputSchema) ? descriptor.inputSchema : null;
718
+ if (!schema) return [];
719
+ const inputDefaults = descriptor.configSchema?.["x-plugmatica-input-defaults"] === true;
720
+ const mappings = node.inputMappings ?? {};
721
+ const fields = [];
722
+ for (const path of visiblePaths(schema)) {
723
+ if (fields.length >= MAX_PRESENTATION_FIELDS) break;
724
+ if (pathIsResource(path, descriptor)) continue;
725
+ const parts = segments2(path);
726
+ const field = parts ? fieldAt(schema, parts) : void 0;
727
+ if (!parts || !field) continue;
728
+ let required = true;
729
+ let current = schema;
730
+ for (const part of parts) {
731
+ required &&= Array.isArray(current.required) && current.required.includes(part);
732
+ current = record(current.properties) && record(current.properties[part]) ? current.properties[part] : {};
733
+ }
734
+ const expression = mappings[path]?.expression;
735
+ const trimmed = typeof expression === "string" ? expression.trim() : "";
736
+ const literal = trimmed ? literalExpression(trimmed) : null;
737
+ const configuredLiteral = valueAt(node.config, parts);
738
+ const mode = trimmed ? literal ? "fixed" : "mapped" : inputDefaults && configuredLiteral !== void 0 ? "fixed" : "unset";
739
+ const referencedNodeId = trimmed ? directWorkflowNodeSource(trimmed) : void 0;
740
+ const unreachable = upstreamNodeIds !== void 0 && referencedNodeId !== void 0 && !upstreamNodeIds.has(referencedNodeId);
741
+ const configured = !unreachable && (mode === "mapped" || mode === "fixed" && workflowFieldHasValue(trimmed ? literal?.value : configuredLiteral));
742
+ fields.push(Object.freeze({ path, required, mode, configured }));
743
+ }
744
+ return Object.freeze(fields);
745
+ }
746
+
747
+ export { DEFAULT_WORKFLOW_FIELD_LABELS, WORKFLOW_NODE_UI_CONTRACT, WORKFLOW_NODE_UI_SURFACE, createWorkflowNodeFields, defineWorkflowNode, dependencyEntity, matchPluginRoute, normalizePluginPath, ownerEntity, projectWorkflowNodePresentationFields, usePluginCurrentPath, usePluginRouteMatch, useWorkflowNodeField, workflowFieldHasValue, workflowNodeUiTargets, workflowUpstreamNodeIds };
748
+ //# sourceMappingURL=index.js.map
749
+ //# sourceMappingURL=index.js.map