@w6w/embed 0.2.29 → 0.2.31

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.
Files changed (76) hide show
  1. package/dist/{CreateFunctionModal-CCYi9deY.js → CreateFunctionModal-glk2zg1r.js} +28 -27
  2. package/dist/{CreateFunctionModal-CCYi9deY.js.map → CreateFunctionModal-glk2zg1r.js.map} +1 -1
  3. package/dist/{DocumentFormModal-CCIgA7pR.js → DocumentFormModal-Cw85R4wk.js} +2 -2
  4. package/dist/{DocumentFormModal-CCIgA7pR.js.map → DocumentFormModal-Cw85R4wk.js.map} +1 -1
  5. package/dist/{ImportSpecModal-DoxsVxru.js → ImportSpecModal-fU5RsVTa.js} +2 -2
  6. package/dist/{ImportSpecModal-DoxsVxru.js.map → ImportSpecModal-fU5RsVTa.js.map} +1 -1
  7. package/dist/WorkflowEditor-B-Wc_r4X.js +1140 -0
  8. package/dist/WorkflowEditor-B-Wc_r4X.js.map +1 -0
  9. package/dist/callable-record-Bhxim8C1.js +14 -0
  10. package/dist/callable-record-Bhxim8C1.js.map +1 -0
  11. package/dist/callables-B49tS2vv.js +297 -0
  12. package/dist/callables-B49tS2vv.js.map +1 -0
  13. package/dist/{document-sources-DNmBojx6.js → document-sources-Khcw2zB5.js} +16 -16
  14. package/dist/document-sources-Khcw2zB5.js.map +1 -0
  15. package/dist/draft.mjs +1 -1
  16. package/dist/editor/WorkflowInputsModal.d.ts +12 -0
  17. package/dist/editor/WorkflowVariablesEditor.d.ts +1 -1
  18. package/dist/{editor-tools--Y3wlBZE.js → editor-tools-Ch1cAE4F.js} +434 -377
  19. package/dist/editor-tools-Ch1cAE4F.js.map +1 -0
  20. package/dist/editor.mjs +1 -1
  21. package/dist/editors.mjs +85 -85
  22. package/dist/endpoints-zOuwci2U.js +136 -0
  23. package/dist/endpoints-zOuwci2U.js.map +1 -0
  24. package/dist/fields-CXHRR5eK.js +28 -0
  25. package/dist/fields-CXHRR5eK.js.map +1 -0
  26. package/dist/forms.mjs +1 -1
  27. package/dist/index.mjs +91 -91
  28. package/dist/index.mjs.map +1 -1
  29. package/dist/lib/callable-duplicate.d.ts +26 -0
  30. package/dist/lib/recent-activity.d.ts +2 -2
  31. package/dist/lib/variable-preview.d.ts +6 -0
  32. package/dist/lib/workflow-version.d.ts +19 -2
  33. package/dist/lib.mjs +41 -40
  34. package/dist/lib.mjs.map +1 -1
  35. package/dist/lists/AiKeyCreate.d.ts +20 -0
  36. package/dist/lists/CallableKindList.d.ts +21 -2
  37. package/dist/lists/CallableRowParts.d.ts +38 -0
  38. package/dist/lists/CredentialCreate.d.ts +17 -17
  39. package/dist/lists/CredentialDetail.d.ts +2 -0
  40. package/dist/lists/CredentialFields.d.ts +18 -0
  41. package/dist/lists/CredentialList.d.ts +35 -3
  42. package/dist/lists/EndpointList.d.ts +2 -1
  43. package/dist/lists/WorkflowList.d.ts +2 -1
  44. package/dist/lists.d.ts +2 -0
  45. package/dist/lists.mjs +2185 -1615
  46. package/dist/lists.mjs.map +1 -1
  47. package/dist/rail.mjs +1 -1
  48. package/dist/repos/callables.d.ts +23 -0
  49. package/dist/repos/fields.d.ts +4 -1
  50. package/dist/repos.mjs +287 -284
  51. package/dist/settings-rail-BjsTjg2u.js +22 -0
  52. package/dist/settings-rail-BjsTjg2u.js.map +1 -0
  53. package/dist/spec-export-BtnoV0ex.js +33 -0
  54. package/dist/spec-export-BtnoV0ex.js.map +1 -0
  55. package/dist/spec-import-CGPqUUjN.js +272 -0
  56. package/dist/spec-import-CGPqUUjN.js.map +1 -0
  57. package/dist/{use-callable-draft-DCauHt5o.js → use-callable-draft-DjW7_9qb.js} +8 -7
  58. package/dist/{use-callable-draft-DCauHt5o.js.map → use-callable-draft-DjW7_9qb.js.map} +1 -1
  59. package/package.json +5 -5
  60. package/src/styles.css +221 -10
  61. package/dist/WorkflowEditor-CBUwh85L.js +0 -1117
  62. package/dist/WorkflowEditor-CBUwh85L.js.map +0 -1
  63. package/dist/callables-tOlflvbl.js +0 -151
  64. package/dist/callables-tOlflvbl.js.map +0 -1
  65. package/dist/document-sources-DNmBojx6.js.map +0 -1
  66. package/dist/editor-tools--Y3wlBZE.js.map +0 -1
  67. package/dist/endpoints-DArAqoLT.js +0 -233
  68. package/dist/endpoints-DArAqoLT.js.map +0 -1
  69. package/dist/fields-DvS8XZFc.js +0 -21
  70. package/dist/fields-DvS8XZFc.js.map +0 -1
  71. package/dist/settings-rail--GdRMusb.js +0 -33
  72. package/dist/settings-rail--GdRMusb.js.map +0 -1
  73. package/dist/spec-export-DMMET5VM.js +0 -189
  74. package/dist/spec-export-DMMET5VM.js.map +0 -1
  75. package/dist/spec-import-0B6oUewa.js +0 -116
  76. package/dist/spec-import-0B6oUewa.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"endpoints-zOuwci2U.js","sources":["../src/repos/functions.ts","../src/repos/endpoints.ts"],"sourcesContent":["import { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { path, type W6WClient } from \"@w6w/sdk\";\nimport type { FunctionSummary as SdkFunctionSummary } from \"@w6w/sdk/console\";\nimport { useEmbedClient } from \"../draft/client-context.ts\";\n/**\n * The Function-bound facade over the kind-parametrised repo (`src/repos/callables.ts`, T4.2.1).\n *\n * Everything here that is not Function-specific is one line delegating to `callables.ts` with\n * `\"function\"` bound in — the list/get queries, the save mutation, archive and delete — so the\n * Function arm of every kind-wide behaviour has exactly ONE implementation to fix. What stays is\n * what only a Function has: the `manifestVersion: \"2\"` literal, the SDK's Function type re-exports,\n * the `valid`-carrying summary widening, and the run-plane invoke (`client.request`)\n * that no other kind's page uses.\n *\n * The delegations keep their original names and call shapes on purpose: `ui/rail/SettingsTool.tsx`,\n * `ui/rail/AliasesTool.tsx`, `ui/rail/ErrorHandlingTool.tsx`, `components/TargetSelector.tsx`,\n * `components/FunctionIdentityModal.tsx` and `api/w6wApiFacade.tsx` all import from here, and this\n * node moves no behaviour — only where the code lives.\n */\nimport { callableKey } from \"../lib/callable-kind.ts\";\nimport { invalidateSavedCallable } from \"../lib/save-invalidation.ts\";\nimport {\n callableListKey,\n useArchiveCallableMutation,\n useCallableListQuery,\n useCallableQuery,\n useDeleteCallableMutation,\n useSaveCallableMutation,\n} from \"./callables.ts\";\n\nexport type {\n FunctionDef,\n FunctionImpl,\n FunctionInput,\n FunctionOutputField,\n} from \"@w6w/sdk/console\";\n\n/** A Function list row — the SDK's own summary (it carries `archivedAt` since W-12). */\nexport type FunctionSummary = SdkFunctionSummary;\n\n/** The list key {@link useFunctionsQuery} reads — `callables.ts`'s own\n * `callableListKey(\"function\")`, kept as a named export because\n * `lib/spec-import-invalidation.ts` invalidates it by value. */\nexport const functionsKey = callableListKey(\"function\");\n\n/** Function definitions carry `manifestVersion: \"2\"` - the one literal, shared\n * by the editor's blank draft and the create modal's first POST. */\nexport const FUNCTION_MANIFEST_VERSION = \"2\";\n\nexport function listFunctions(client: W6WClient) {\n return client.console.functions.list();\n}\n\nexport function useFunctionsQuery(enabled = true) {\n return useCallableListQuery<FunctionSummary>(\"function\", enabled);\n}\n\nexport const functionKey = (id: string) => callableKey(\"function\", id);\n\n/** The Function arm's own reader: the SDK's typed `get`, whose `{...function, valid}` splice is\n * what `FunctionEditor` hydrates its draft from (pin 5 — the server computes `valid`; studio\n * never reimplements the check). */\nexport function getFunction(client: W6WClient, id: string) {\n return client.console.functions.get(id);\n}\n\nexport function useFunctionQuery(id: string, enabled = true) {\n return useCallableQuery<Awaited<ReturnType<typeof getFunction>>>(\"function\", id, enabled);\n}\n\nexport function useSaveFunctionMutation() {\n return useSaveCallableMutation(\"function\");\n}\n\n/**\n * The GUARDED Function save: `console.functions.upsert(definition, {ifUnmodifiedSince})`, so a\n * save made from a stale copy answers `409 function_stale` instead of overwriting the newer one.\n * `ifUnmodifiedSince` is REQUIRED in the variables (pass `null` to opt out explicitly) so a call\n * site cannot forget the token; it is the `updatedAt` of the copy the definition was edited from\n * (`callableRecord(\"function\", …).updatedAt`). Same invalidation as {@link useSaveFunctionMutation}\n * (list + the saved resource's key); resolves `{id, key, updatedAt}`. Additive: the unguarded\n * hook's `mutate(definition)` shape is unchanged.\n */\nexport function useGuardedSaveFunctionMutation() {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: (vars: { definition: unknown; ifUnmodifiedSince: string | null }) =>\n apiClient.console.functions.upsert(vars.definition as never, {\n ifUnmodifiedSince: vars.ifUnmodifiedSince,\n }),\n onSuccess: (saved) => invalidateSavedCallable(qc, functionsKey, functionKey(saved.id)),\n });\n}\n\n/**\n * One test invoke's result: the Function's own output, plus the platform's\n * record of the attempt.\n *\n * The two are kept apart rather than merged because they answer different\n * questions, and merging them is what the invocation envelope exists to stop:\n * a vendor payload reading `{\"statusCode\": 202}` is SendGrid describing its own\n * request, while `status` here is whether w6w considered the call a success.\n * The frame fields are optional — an older server sends only the output.\n */\nexport interface FunctionInvokeResult {\n output: unknown;\n invocationId?: string;\n status?: string;\n durationMs?: number;\n}\n\n/**\n * `POST /functions/:id/invoke` through the `client.request` escape hatch (D2: no wrappers change).\n * The route answers the invocation frame `{ kind: \"function\", output, invocationId, status,\n * durationMs }`. `allowUnpublished: true` is sent ONLY when the caller opts in (the editor's Test\n * invoke hook); every other caller keeps the publish gate, so the key is absent otherwise.\n */\nexport function invokeFunction(\n client: W6WClient,\n id: string,\n inputs: Record<string, unknown>,\n opts?: { allowUnpublished?: boolean },\n): Promise<FunctionInvokeResult> {\n const body: Record<string, unknown> = { inputs };\n if (opts?.allowUnpublished === true) body.allowUnpublished = true;\n return client\n .request<Record<string, unknown>>({\n method: \"POST\",\n path: path`/functions/${id}/invoke`,\n body,\n })\n .then(({ body: res }) => ({\n output: res.output,\n invocationId: res.invocationId as string | undefined,\n status: res.status as string | undefined,\n durationMs: res.durationMs as number | undefined,\n }));\n}\n\nexport function useInvokeFunctionMutation() {\n const apiClient = useEmbedClient();\n return useMutation({\n mutationFn: (vars: { id: string; inputs: Record<string, unknown> }) =>\n invokeFunction(apiClient, vars.id, vars.inputs, { allowUnpublished: true }),\n });\n}\n\n/**\n * T4.1.1/A7/D-I0-7: `POST /functions/:id/archive`, `DELETE /functions/:id` — the Function arm of\n * `callables.ts`'s generic pair (the plain `apiClient.request()` escape hatch, NOT a typed\n * `@w6w/sdk` method, which would drag `packages/wrappers` into this task's scope for two internal\n * routes). Both invalidate `functionsKey`, so the list's `archivedAt` refreshes and the rail's\n * Delete control appears in Archive's place.\n */\nexport function useArchiveFunctionMutation() {\n return useArchiveCallableMutation(\"function\");\n}\n\nexport function useDeleteFunctionMutation() {\n return useDeleteCallableMutation(\"function\");\n}\n","import { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { path, type W6WClient } from \"@w6w/sdk\";\nimport type {\n EndpointInvokeResult,\n EndpointDef as SdkEndpointDef,\n EndpointSummary as SdkEndpointSummary,\n EndpointTarget as SdkEndpointTarget,\n} from \"@w6w/sdk/console\";\n/**\n * The Endpoint-bound facade over the kind-parametrised repo (`src/repos/callables.ts`, T4.2.2).\n *\n * Everything here that is not Endpoint-specific is one line delegating to `callables.ts` with\n * `\"endpoint\"` bound in — the list/get queries, archive and delete — so the Endpoint arm of every\n * kind-wide behaviour has exactly ONE implementation to fix (the shape `repos/functions.ts` took in\n * T4.2.1, and the \"keep the facade's exports\" rule that module documents). What stays is what only\n * an Endpoint has: the `manifestVersion: \"2\"` literal, the SDK's Endpoint type re-exports, the\n * `status`/`incomplete`/`archivedAt`-carrying summary widening with its one reader\n * {@link isEndpointDraft}, the server-rendered `invokeUrls[]` widening, the synchronous invoke\n * (`client.console.endpoints.invoke`), and the SAVE — whose 201 carries those `invokeUrls[]` back to\n * the editor's URL card, which is why its `mutationFn` is the one arm the generic `saveCallable`\n * cannot serve.\n *\n * The delegations keep their original names and call shapes on purpose: `ui/rail/SettingsTool.tsx`,\n * `ui/rail/AliasesTool.tsx`, `ui/rail/ErrorHandlingTool.tsx`, `components/TargetSelector.tsx`,\n * `components/EndpointIdentityModal.tsx`, `repos/versions.ts` (the revert arm's `endpointKey`) and\n * `repos/spec-import.ts` (`endpointsKey`) all import from here, and this node moves no behaviour —\n * only where the code lives. The two key exports stay byte-identical because both are the builders\n * `callables.ts` already documents as frozen (`[\"endpoints\"]`, `[\"endpoint\", id]`).\n */\nimport { callableKey } from \"../lib/callable-kind.ts\";\nimport { invalidateSavedCallable } from \"../lib/save-invalidation.ts\";\n\nexport type {\n ActionTarget,\n CallableRef,\n CallableOnError,\n ErrorHandlerTarget,\n EndpointAuthMode,\n EndpointInput,\n EndpointInvokeResult,\n EndpointSecurity,\n EndpointTarget,\n ErrorReroute,\n Exposure,\n RetryPolicy,\n} from \"@w6w/sdk/console\";\nexport { SECRET_MASK } from \"@w6w/sdk/console\";\nimport { useEmbedClient } from \"../draft/client-context.ts\";\nimport {\n callableListKey,\n useArchiveCallableMutation,\n useCallableListQuery,\n useCallableQuery,\n useDeleteCallableMutation,\n} from \"./callables.ts\";\n\n/** An Endpoint's OWN target: the alias-only `endpoint` arm excluded, mirroring the\n * server fence in admin/endpoints.ts's validateDefinition. Aliases use the full union\n * (`EndpointTarget`, re-exported above verbatim). */\nexport type EndpointOwnTarget = Exclude<SdkEndpointTarget, { kind: \"endpoint\" }>;\nexport type EndpointDef = Omit<SdkEndpointDef, \"target\"> & { target: EndpointOwnTarget };\n\n/**\n * One entry of the `invokeUrls[]` array the server renders on `GET\n * /endpoints/:id` and the `POST /endpoints` 201 (T3.4.1, `admin/endpoints.ts`'s\n * `InvokeUrlEntry` — the shapes are kept in sync by hand, not shared, because\n * `@w6w/sdk` does not type this field yet: it is server-fresh and\n * `packages/wrappers` publishes in lockstep at one `VERSION` across four\n * languages, outside this project's boundary (HITL-10). `entries[0]` is always\n * the platform entry; every entry after it is one of the tenant's domains.\n * `default` mirrors the tenant's stored default domain and, since D-S1\n * (intake T-0.2), it is what CHOOSES the open-on entry: absent an\n * in-session pick, the URL card opens on whichever entry carries it,\n * falling back to `entries[0]` only when no entry does. `resolves` is a\n * static host comparison the server already made; the client never\n * re-derives it.\n */\nexport interface InvokeUrlOption {\n domain: string;\n default: boolean;\n url: string;\n urlByKey?: string;\n resolves: boolean;\n}\n\n/** The two SDK-typed URL fields, widened with the untyped `invokeUrls[]`\n * array — the ONE seam `getEndpoint`, the save mutation and the editor's own\n * 201 read all widen through, so `EndpointsPage.tsx` never casts. */\ntype WithInvokeUrls = {\n invokeUrl: string;\n invokeUrlByKey?: string;\n invokeUrls?: InvokeUrlOption[];\n};\n\n/** An Endpoint list row — the SDK's own summary (`status`, `incomplete` and `archivedAt` are\n * on it since W-12), read for draft-ness only through {@link isEndpointDraft}. */\nexport type EndpointSummary = SdkEndpointSummary;\n\n/** Is this row a draft — not authorised to dispatch (HITL-7/HITL-8,\n * `rfcs/endpoint.md` § Amendment — 2026-08-14b)? Prefers the server's `status`\n * field (`!== \"ready\"`), falling back to the older `incomplete` boolean only\n * when `status` is absent (a server that has not shipped it yet). The sole\n * reader of both fields in studio; every \"unfinished\" UI decision (the\n * list's tag, and any future one) calls this rather than reading either\n * field inline. */\nexport function isEndpointDraft(ep: Pick<EndpointSummary, \"status\" | \"incomplete\">): boolean {\n return ep.status !== undefined ? ep.status !== \"ready\" : ep.incomplete === true;\n}\n\n/** Endpoint definitions carry `manifestVersion: \"2\"` — the one literal, shared\n * by the editor's blank draft and the create modal's first POST. */\nexport const ENDPOINT_MANIFEST_VERSION = \"2\";\n\n/** The list key {@link useEndpointsQuery} reads — `callables.ts`'s own\n * `callableListKey(\"endpoint\")` (byte-identical `[\"endpoints\"]`), kept as a named export because\n * `repos/spec-import.ts` invalidates it by value. */\nexport const endpointsKey = callableListKey(\"endpoint\");\n\nexport function useEndpointsQuery(enabled = true) {\n return useCallableListQuery<EndpointSummary>(\"endpoint\", enabled);\n}\n\n/** Fetch one Endpoint. Widens the SDK's return once — the server sends\n * `invokeUrls[]` (T3.4.1) that `@w6w/sdk`'s typed `get()` does not know about\n * yet; see {@link WithInvokeUrls}. */\nexport function getEndpoint(\n client: W6WClient,\n id: string,\n): Promise<{ endpoint: EndpointDef } & WithInvokeUrls> {\n return client.console.endpoints.get(id) as Promise<{ endpoint: EndpointDef } & WithInvokeUrls>;\n}\n\n/** The single-resource key — `callables.ts`'s own `callableKey(\"endpoint\", id)` (byte-identical\n * `[\"endpoint\", id]`), kept as a named export because `repos/versions.ts`'s revert arm invalidates\n * it by value. */\nexport const endpointKey = (id: string) => callableKey(\"endpoint\", id);\n\n/** `TargetSelector`'s `endpoint` arm needs one Endpoint's own `input` contract\n * to project into fields — mirrors `useFunctionQuery`/`useWorkflowQuery`\n * (`repos/functions.ts`/`repos/workflows.ts`) exactly. */\nexport function useEndpointQuery(id: string, enabled = true) {\n return useCallableQuery<Awaited<ReturnType<typeof getEndpoint>>>(\"endpoint\", id, enabled);\n}\n\n/**\n * The Endpoint arm's SAVE — the one delegated name whose `mutationFn` is NOT `callables.ts`'s\n * `saveCallable`: that helper normalises every kind's success envelope down to `{id, key}` for the\n * invalidation below, while this kind's 201 also carries the fresh server-rendered `invokeUrl`/\n * `invokeUrlByKey`/`invokeUrls[]` the editor's URL card renders from (`onSaveSuccess` in\n * `EndpointsPage.tsx`). Its KEYS and its invalidation, though, are the generic pair's — so the\n * \"which keys does an Endpoint save refresh\" answer still has one home.\n */\nexport function useSaveEndpointMutation() {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n // Same widening as `getEndpoint` — the save's 201 carries `invokeUrls[]` too.\n mutationFn: (definition: unknown) =>\n apiClient.console.endpoints.upsert(definition as never) as Promise<\n { endpoint: { id: string; key: string } } & WithInvokeUrls\n >,\n onSuccess: (saved) => invalidateSavedCallable(qc, endpointsKey, endpointKey(saved.endpoint.id)),\n });\n}\n\n/**\n * The GUARDED Endpoint save: `console.endpoints.upsert(definition, {ifUnmodifiedSince})`, so a\n * save from a stale copy answers `409 endpoint_stale`. Variables and invalidation as\n * {@link useSaveEndpointMutation}'s, plus the required token (`null` opts out explicitly; it is\n * `callableRecord(\"endpoint\", …).updatedAt`, the envelope's TOP-LEVEL `updatedAt`). Resolves the\n * verbatim upsert body (`{endpoint:{id,key}, invokeUrl, …, updatedAt}`). Additive: the unguarded\n * hook's `mutate(definition)` shape is unchanged.\n */\nexport function useGuardedSaveEndpointMutation() {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: (vars: { definition: unknown; ifUnmodifiedSince: string | null }) =>\n apiClient.console.endpoints.upsert(vars.definition as never, {\n ifUnmodifiedSince: vars.ifUnmodifiedSince,\n }) as Promise<{ endpoint: { id: string; key: string }; updatedAt: string } & WithInvokeUrls>,\n onSuccess: (saved) => invalidateSavedCallable(qc, endpointsKey, endpointKey(saved.endpoint.id)),\n });\n}\n\n/**\n * `POST /endpoints/:id/invoke` through `client.request` (D2). Answers `{ kind, output }`, or a 202\n * `{ kind: \"workflow\", runId }` (success). `allowUnpublished: true` only when the caller opts in.\n */\nexport function invokeEndpoint(\n client: W6WClient,\n id: string,\n input: Record<string, unknown>,\n opts?: { allowUnpublished?: boolean },\n): Promise<EndpointInvokeResult> {\n const body: Record<string, unknown> = { input };\n if (opts?.allowUnpublished === true) body.allowUnpublished = true;\n return client\n .request<EndpointInvokeResult>({\n method: \"POST\",\n path: path`/endpoints/${id}/invoke`,\n body,\n })\n .then((res) => res.body as EndpointInvokeResult);\n}\n\nexport function useInvokeEndpointMutation() {\n const apiClient = useEmbedClient();\n return useMutation({\n mutationFn: (vars: { id: string; input: Record<string, unknown> }) =>\n invokeEndpoint(apiClient, vars.id, vars.input, { allowUnpublished: true }),\n });\n}\n\n/**\n * T4.1.1/A7/D-I0-7: `POST /endpoints/:id/archive` — the Endpoint arm of `callables.ts`'s generic\n * pair (the plain `apiClient.request()` escape hatch, NOT a typed `@w6w/sdk` method, which would\n * drag `packages/wrappers` into this task's scope for one internal route). Invalidates\n * `endpointsKey`, so the list's `archivedAt` refreshes and the rail's Delete control appears in\n * Archive's place.\n */\nexport function useArchiveEndpointMutation() {\n return useArchiveCallableMutation(\"endpoint\");\n}\n\n/** `DELETE /endpoints/:id` — the Endpoint arm of the same generic pair. */\nexport function useDeleteEndpointMutation() {\n return useDeleteCallableMutation(\"endpoint\");\n}\n"],"names":["functionsKey","callableListKey","FUNCTION_MANIFEST_VERSION","listFunctions","client","useFunctionsQuery","enabled","useCallableListQuery","functionKey","id","callableKey","getFunction","useFunctionQuery","useCallableQuery","useSaveFunctionMutation","useSaveCallableMutation","useGuardedSaveFunctionMutation","apiClient","useEmbedClient","qc","useQueryClient","useMutation","vars","saved","invalidateSavedCallable","invokeFunction","inputs","opts","body","path","res","useInvokeFunctionMutation","useArchiveFunctionMutation","useArchiveCallableMutation","useDeleteFunctionMutation","useDeleteCallableMutation","isEndpointDraft","ep","ENDPOINT_MANIFEST_VERSION","endpointsKey","useEndpointsQuery","getEndpoint","endpointKey","useEndpointQuery","useSaveEndpointMutation","definition","useGuardedSaveEndpointMutation","invokeEndpoint","input","useInvokeEndpointMutation","useArchiveEndpointMutation","useDeleteEndpointMutation"],"mappings":";;;;;AA2CO,MAAMA,IAAeC,EAAgB,UAAU,GAIzCC,IAA4B;AAElC,SAASC,EAAcC,GAAmB;AAC/C,SAAOA,EAAO,QAAQ,UAAU,KAAA;AAClC;AAEO,SAASC,EAAkBC,IAAU,IAAM;AAChD,SAAOC,EAAsC,YAAYD,CAAO;AAClE;AAEO,MAAME,IAAc,CAACC,MAAeC,EAAY,YAAYD,CAAE;AAK9D,SAASE,EAAYP,GAAmBK,GAAY;AACzD,SAAOL,EAAO,QAAQ,UAAU,IAAIK,CAAE;AACxC;AAEO,SAASG,EAAiBH,GAAYH,IAAU,IAAM;AAC3D,SAAOO,EAA0D,YAAYJ,GAAIH,CAAO;AAC1F;AAEO,SAASQ,IAA0B;AACxC,SAAOC,EAAwB,UAAU;AAC3C;AAWO,SAASC,IAAiC;AAC/C,QAAMC,IAAYC,EAAA,GACZC,IAAKC,EAAA;AACX,SAAOC,EAAY;AAAA,IACjB,YAAY,CAACC,MACXL,EAAU,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B,IAA6B;AAC3C,SAAOjB,EAA2B,UAAU;AAC9C;AAGO,SAASkB,IAA4B;AAC1C,SAAOhB,EAA0B,UAAU;AAC7C;"}
@@ -0,0 +1,28 @@
1
+ import { path as n, ApiError as c } from "@w6w/sdk";
2
+ function l(t, i, s, e, r) {
3
+ return a(t, n`/apps/${i}/actions/${s}/fields`, e, r);
4
+ }
5
+ function u(t, i, s, e, r) {
6
+ return a(t, n`/apps/${i}/triggers/${s}/fields`, e, r);
7
+ }
8
+ async function a(t, i, s, e) {
9
+ try {
10
+ return (await t.request({
11
+ method: "POST",
12
+ path: i,
13
+ body: s,
14
+ signal: e == null ? void 0 : e.signal
15
+ })).body;
16
+ } catch (r) {
17
+ if (r instanceof c && r.status === 424)
18
+ return {
19
+ fields: Object.fromEntries(s.fields.map((o) => [o, { error: r.message }]))
20
+ };
21
+ throw r;
22
+ }
23
+ }
24
+ export {
25
+ u as a,
26
+ l as r
27
+ };
28
+ //# sourceMappingURL=fields-CXHRR5eK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fields-CXHRR5eK.js","sources":["../src/repos/fields.ts"],"sourcesContent":["import type { W6WClient } from \"@w6w/sdk\";\nimport { path, ApiError } from \"@w6w/sdk\";\n/**\n * Dynamic-field resolution — `POST /apps/:id/actions/:key/fields` (and a trigger's subscription\n * form, `POST /apps/:id/triggers/:key/fields`) over `client.request()`.\n * A 424 (the vendor lookup failed) becomes a per-field error result so one bad lookup does not\n * blank the form; every other failure (400/403/404/network/abort) rethrows for the ui to handle.\n */\n\n/**\n * Structural mirror of ui's `W6WApi.resolveActionFields` shapes (this barrel may not import\n * `@w6w/ui`); the facade/UiBridge assignment typechecks against W6WApi structurally.\n */\nexport interface ResolveActionFieldsBody {\n connectionId: string;\n version?: string;\n reason: \"init\" | \"change\";\n form: Record<string, unknown>;\n previous?: Record<string, unknown>;\n changed?: string[];\n fields: string[];\n unresolved: string[];\n}\nexport interface ResolveActionFieldsResult {\n fields: Record<\n string,\n { options?: { value: string | number; label: string; description?: string }[]; error?: string }\n >;\n}\nexport interface ResolveActionFieldsOpts {\n signal?: AbortSignal;\n}\n\nexport function resolveActionFields(\n client: W6WClient,\n appId: string,\n actionKey: string,\n body: ResolveActionFieldsBody,\n opts?: ResolveActionFieldsOpts,\n): Promise<ResolveActionFieldsResult> {\n return postFields(client, path`/apps/${appId}/actions/${actionKey}/fields`, body, opts);\n}\n\n/** A trigger's subscription form: the same body, answers and 424 handling as an action's. */\nexport function resolveTriggerFields(\n client: W6WClient,\n appId: string,\n triggerKey: string,\n body: ResolveActionFieldsBody,\n opts?: ResolveActionFieldsOpts,\n): Promise<ResolveActionFieldsResult> {\n return postFields(client, path`/apps/${appId}/triggers/${triggerKey}/fields`, body, opts);\n}\n\nasync function postFields(\n client: W6WClient,\n url: string,\n body: ResolveActionFieldsBody,\n opts?: ResolveActionFieldsOpts,\n): Promise<ResolveActionFieldsResult> {\n try {\n const res = await client.request<ResolveActionFieldsResult>({\n method: \"POST\",\n path: url,\n body,\n signal: opts?.signal,\n });\n return res.body;\n } catch (err) {\n if (err instanceof ApiError && err.status === 424) {\n return {\n fields: Object.fromEntries(body.fields.map((k) => [k, { error: err.message }])),\n };\n }\n throw err;\n }\n}\n"],"names":["resolveActionFields","client","appId","actionKey","body","opts","postFields","path","resolveTriggerFields","triggerKey","url","err","ApiError","k"],"mappings":";AAiCO,SAASA,EACdC,GACAC,GACAC,GACAC,GACAC,GACoC;AACpC,SAAOC,EAAWL,GAAQM,UAAaL,CAAK,YAAYC,CAAS,WAAWC,GAAMC,CAAI;AACxF;AAGO,SAASG,EACdP,GACAC,GACAO,GACAL,GACAC,GACoC;AACpC,SAAOC,EAAWL,GAAQM,UAAaL,CAAK,aAAaO,CAAU,WAAWL,GAAMC,CAAI;AAC1F;AAEA,eAAeC,EACbL,GACAS,GACAN,GACAC,GACoC;AACpC,MAAI;AAOF,YANY,MAAMJ,EAAO,QAAmC;AAAA,MAC1D,QAAQ;AAAA,MACR,MAAMS;AAAA,MACN,MAAAN;AAAA,MACA,QAAQC,KAAA,gBAAAA,EAAM;AAAA,IAAA,CACf,GACU;AAAA,EACb,SAASM,GAAK;AACZ,QAAIA,aAAeC,KAAYD,EAAI,WAAW;AAC5C,aAAO;AAAA,QACL,QAAQ,OAAO,YAAYP,EAAK,OAAO,IAAI,CAACS,MAAM,CAACA,GAAG,EAAE,OAAOF,EAAI,QAAA,CAAS,CAAC,CAAC;AAAA,MAAA;AAGlF,UAAMA;AAAA,EACR;AACF;"}
package/dist/forms.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- import { C as _e, a as Je } from "./CreateFunctionModal-CCYi9deY.js";
2
+ import { C as _e, a as Je } from "./CreateFunctionModal-glk2zg1r.js";
3
3
  import { jsx as t, jsxs as l, Fragment as te } from "react/jsx-runtime";
4
4
  import { ApiError as I } from "@w6w/sdk";
5
5
  import { EmptyState as A, DataTable as P, RowActionsMenu as U, useEnterSubmit as T, BudgetMeter as ie } from "@w6w/ui";
package/dist/index.mjs CHANGED
@@ -1,130 +1,130 @@
1
1
  "use client";
2
- import { jsx as c, jsxs as N } from "react/jsx-runtime";
2
+ import { jsx as l, jsxs as N } from "react/jsx-runtime";
3
3
  import { QueryClientProvider as O, QueryClient as G, useQuery as z } from "@tanstack/react-query";
4
4
  import { W6WProvider as J, useW6WClient as P, useW6WSession as H, createW6WUiAdapter as V } from "@w6w/react";
5
5
  import { W6WUIProvider as X } from "@w6w/ui";
6
- import { useState as j, useRef as x, useEffect as w, useCallback as R, useMemo as v, useContext as Y, createContext as Z } from "react";
6
+ import { useState as v, useRef as x, useEffect as j, useCallback as F, useMemo as g, useContext as Y, createContext as Z } from "react";
7
7
  import { E as _ } from "./client-context-CX61Bgw-.js";
8
8
  import { c as ee, D as te } from "./draft-registry-YF0tqNN0.js";
9
9
  import { E as re, a as oe } from "./project-context-Tvp-La7A.js";
10
- import { b as Ne } from "./project-context-Tvp-La7A.js";
11
- import { j as ne } from "./connections-CzsCyIxY.js";
12
- import { D as se } from "./credentials-4Nf2GfMc.js";
10
+ import { b as Oe } from "./project-context-Tvp-La7A.js";
11
+ import { j as se } from "./connections-CzsCyIxY.js";
12
+ import { D as ne } from "./credentials-4Nf2GfMc.js";
13
13
  import { e as ie, c as ue } from "./data-stores-UeQvwVCa.js";
14
- import { r as ae } from "./fields-DvS8XZFc.js";
14
+ import { r as ae, a as le } from "./fields-CXHRR5eK.js";
15
15
  import { l as ce } from "./models-CI0vLJ6o.js";
16
- import { path as q } from "@w6w/sdk";
17
- import { s as le, t as de, J as fe } from "./workflows-Dz8LMjnt.js";
18
- import { E as pe } from "./theme-context-E2ZhlXDX.js";
19
- class me extends Error {
20
- constructor(s) {
21
- super("The w6w API rejected the embed session token (401).", { cause: s }), this.name = "EmbedAuthError";
16
+ import { path as T } from "@w6w/sdk";
17
+ import { s as de, t as fe, J as pe } from "./workflows-Dz8LMjnt.js";
18
+ import { E as me } from "./theme-context-E2ZhlXDX.js";
19
+ class ye extends Error {
20
+ constructor(n) {
21
+ super("The w6w API rejected the embed session token (401).", { cause: n }), this.name = "EmbedAuthError";
22
22
  }
23
23
  }
24
- function ye(n, s, e) {
24
+ function he(s, n, e) {
25
25
  if (e) return { status: "error", error: e };
26
- switch (n) {
26
+ switch (s) {
27
27
  case "ready":
28
28
  case "renewing":
29
29
  return { status: "ready", error: null };
30
30
  case "error":
31
- return { status: "error", error: s };
31
+ return { status: "error", error: n };
32
32
  case "loading":
33
33
  case "expired":
34
34
  return { status: "connecting", error: null };
35
35
  }
36
36
  }
37
- async function he(n, s) {
38
- return (await n.request({
37
+ async function be(s, n) {
38
+ return (await s.request({
39
39
  method: "POST",
40
- path: q`/subscriptions/${s}/listen`,
40
+ path: T`/subscriptions/${n}/listen`,
41
41
  body: {}
42
42
  })).body;
43
43
  }
44
- async function be(n, s, e, i) {
45
- return (await n.request({
44
+ async function ve(s, n, e, i) {
45
+ return (await s.request({
46
46
  method: "GET",
47
- path: q`/subscriptions/${s}/listen/${e}`,
47
+ path: T`/subscriptions/${n}/listen/${e}`,
48
48
  query: { wait: String((i == null ? void 0 : i.waitSeconds) ?? 0) },
49
49
  signal: i == null ? void 0 : i.signal
50
50
  })).body.session;
51
51
  }
52
- async function je(n, s, e) {
53
- await n.request({
52
+ async function je(s, n, e) {
53
+ await s.request({
54
54
  method: "DELETE",
55
- path: q`/subscriptions/${s}/listen/${e}`
55
+ path: T`/subscriptions/${n}/listen/${e}`
56
56
  });
57
57
  }
58
- function I() {
58
+ function R() {
59
59
  return new G({
60
60
  defaultOptions: { queries: { retry: !1, refetchOnWindowFocus: !1 } }
61
61
  });
62
62
  }
63
- function we({ children: n }) {
64
- return /* @__PURE__ */ c(_, { client: P(), children: n });
63
+ function ge({ children: s }) {
64
+ return /* @__PURE__ */ l(_, { client: P(), children: s });
65
65
  }
66
- function ve({ theme: n, children: s }) {
67
- const e = P(), i = oe(), a = v(() => {
66
+ function we({ theme: s, children: n }) {
67
+ const e = P(), i = oe(), a = g(() => {
68
68
  const t = V(e);
69
- return typeof t.updateConnection != "function" && (t.updateConnection = (r, o) => ne(e, r, o)), se(t, e), typeof t.listModelRoutes != "function" && (t.listModelRoutes = async (r) => {
69
+ return typeof t.updateConnection != "function" && (t.updateConnection = (r, o) => se(e, r, o)), ne(t, e), typeof t.listModelRoutes != "function" && (t.listModelRoutes = async (r) => {
70
70
  const o = r || i;
71
- return o ? (await ce(e, o)).map((f) => ({ name: f.name, model: f.modelId, status: f.status })) : [];
71
+ return o ? (await ce(e, o)).map((c) => ({ name: c.name, model: c.modelId, status: c.status })) : [];
72
72
  }), typeof t.listDataStores != "function" && (t.listDataStores = async (r) => {
73
73
  const o = r || i;
74
74
  return o ? ie(e, o) : [];
75
75
  }), typeof t.listDataStoreEntries != "function" && (t.listDataStoreEntries = async (r, o) => {
76
76
  const u = o.project || i;
77
77
  return u ? ue(e, u, r, o) : { items: [] };
78
- }), typeof t.loadNodeSamples != "function" && (t.loadNodeSamples = (r) => le(e, r)), typeof t.loadTestInputs != "function" && (t.loadTestInputs = (r) => de(e, r)), typeof t.saveTestInput != "function" && (t.saveTestInput = (r, o, u) => fe(e, r, o, u)), typeof t.resolveActionFields != "function" && (t.resolveActionFields = (r, o, u, f) => ae(e, r, o, u, f)), typeof t.startWebhookListen != "function" && (t.startWebhookListen = (r) => he(e, r), t.pollWebhookListen = (r, o, u) => be(e, r, o, u), t.stopWebhookListen = (r, o) => je(e, r, o)), t;
78
+ }), typeof t.loadNodeSamples != "function" && (t.loadNodeSamples = (r) => de(e, r)), typeof t.loadTestInputs != "function" && (t.loadTestInputs = (r) => fe(e, r)), typeof t.saveTestInput != "function" && (t.saveTestInput = (r, o, u) => pe(e, r, o, u)), typeof t.resolveActionFields != "function" && (t.resolveActionFields = (r, o, u, c) => ae(e, r, o, u, c)), typeof t.resolveTriggerFields != "function" && (t.resolveTriggerFields = (r, o, u, c) => le(e, r, o, u, c)), typeof t.startWebhookListen != "function" && (t.startWebhookListen = (r) => be(e, r), t.pollWebhookListen = (r, o, u) => ve(e, r, o, u), t.stopWebhookListen = (r, o) => je(e, r, o)), t;
79
79
  }, [e, i]);
80
- return /* @__PURE__ */ c(X, { api: a, theme: n, children: /* @__PURE__ */ c(pe.Provider, { value: n, children: s }) });
80
+ return /* @__PURE__ */ l(X, { api: a, theme: s, children: /* @__PURE__ */ l(me.Provider, { value: s, children: n }) });
81
81
  }
82
- const F = Z({ status: "connecting", error: null });
83
- function $e() {
84
- return Y(F);
82
+ const I = Z({ status: "connecting", error: null });
83
+ function Ke() {
84
+ return Y(I);
85
85
  }
86
86
  function Ee({
87
- eager: n,
88
- authError: s,
87
+ eager: s,
88
+ authError: n,
89
89
  onAcquire: e,
90
90
  children: i
91
91
  }) {
92
92
  const { status: a, error: t, refresh: r } = H();
93
- w(() => {
94
- n && r();
95
- }, [n, r]), w(() => {
93
+ j(() => {
94
+ s && r();
95
+ }, [s, r]), j(() => {
96
96
  (a === "loading" || a === "renewing") && e();
97
97
  }, [a, e]);
98
- const o = v(
99
- () => ye(a, t, s),
100
- [a, t, s]
98
+ const o = g(
99
+ () => he(a, t, n),
100
+ [a, t, n]
101
101
  );
102
- return /* @__PURE__ */ c(F.Provider, { value: o, children: i });
102
+ return /* @__PURE__ */ l(I.Provider, { value: o, children: i });
103
103
  }
104
104
  function Ce({
105
- identityKey: n,
106
- enabled: s,
105
+ identityKey: s,
106
+ enabled: n,
107
107
  onState: e
108
108
  }) {
109
109
  const i = P(), a = z({
110
110
  queryKey: ["w6w-embed", "default-project"],
111
- enabled: s,
111
+ enabled: n,
112
112
  queryFn: async () => {
113
- const y = (await i.projects.list()).find((l) => l.isDefault === !0);
113
+ const y = (await i.projects.list()).find((d) => d.isDefault === !0);
114
114
  if (!y) throw new Error("The account has no default project.");
115
115
  return y.id;
116
116
  }
117
- }), { isError: t, error: r, data: o } = a, u = v(
117
+ }), { isError: t, error: r, data: o } = a, u = g(
118
118
  () => t ? { project: null, status: "error", error: r } : o !== void 0 ? { project: o, status: "ready" } : { project: null, status: "resolving" },
119
119
  [t, r, o]
120
120
  );
121
- return w(() => {
122
- e(n, u);
123
- }, [n, u, e]), null;
121
+ return j(() => {
122
+ e(s, u);
123
+ }, [s, u, e]), null;
124
124
  }
125
- function Ke({
126
- apiOrigin: n,
127
- getSession: s,
125
+ function Qe({
126
+ apiOrigin: s,
127
+ getSession: n,
128
128
  identityKey: e,
129
129
  fallback: i = null,
130
130
  eager: a = !1,
@@ -132,52 +132,52 @@ function Ke({
132
132
  ready: r,
133
133
  project: o,
134
134
  fetch: u,
135
- children: f
135
+ children: c
136
136
  }) {
137
- const [y] = j(ee), [l, L] = j(() => ({
137
+ const [y] = v(ee), [d, L] = v(() => ({
138
138
  identityKey: e,
139
- queryClient: I()
140
- })), M = e !== l.identityKey, D = x({ apiOrigin: n, project: o, getSession: s });
141
- M || (D.current = { apiOrigin: n, project: o, getSession: s });
142
- const E = D.current, k = x(E.getSession);
143
- k.current = E.getSession;
144
- const [U] = j(() => () => k.current());
145
- w(() => {
146
- if (e === l.identityKey) return;
139
+ queryClient: R()
140
+ })), M = e !== d.identityKey, q = x({ apiOrigin: s, project: o, getSession: n });
141
+ M || (q.current = { apiOrigin: s, project: o, getSession: n });
142
+ const w = q.current, D = x(w.getSession);
143
+ D.current = w.getSession;
144
+ const [U] = v(() => () => D.current());
145
+ j(() => {
146
+ if (e === d.identityKey) return;
147
147
  let p = !1;
148
- const d = () => {
149
- p || L({ identityKey: e, queryClient: I() });
148
+ const f = () => {
149
+ p || L({ identityKey: e, queryClient: R() });
150
150
  };
151
- return l.identityKey === null ? (d(), () => {
151
+ return d.identityKey === null ? (f(), () => {
152
152
  p = !0;
153
- }) : (y.flushAll().then(d, d), () => {
153
+ }) : (y.flushAll().then(f, f), () => {
154
154
  p = !0;
155
155
  });
156
- }, [e, l.identityKey, y]);
157
- const C = l.queryClient;
158
- w(() => () => C.clear(), [C]);
159
- const [S, $] = j(null), K = R((p, d) => {
156
+ }, [e, d.identityKey, y]);
157
+ const E = d.queryClient;
158
+ j(() => () => E.clear(), [E]);
159
+ const [C, $] = v(null), K = F((p, f) => {
160
160
  $(
161
- (b) => b && b.key === p && b.state.project === d.project && b.state.status === d.status && b.state.error === d.error ? b : { key: p, state: d }
161
+ (b) => b && b.key === p && b.state.project === f.project && b.state.status === f.status && b.state.error === f.error ? b : { key: p, state: f }
162
162
  );
163
- }, []), [g, A] = j(null), Q = v(() => {
164
- const p = l.queryClient;
165
- return (d) => {
166
- A({ key: p, error: new me(d) });
163
+ }, []), [S, k] = v(null), Q = g(() => {
164
+ const p = d.queryClient;
165
+ return (f) => {
166
+ k({ key: p, error: new ye(f) });
167
167
  };
168
- }, [l.queryClient]), B = R(() => A(null), []), h = l.identityKey, m = E.project, W = typeof m == "object" && m !== null && !Array.isArray(m) && m.use === "default", T = v(() => typeof m == "string" ? { project: m, status: "ready" } : W ? S && S.key === h ? S.state : { project: null, status: "resolving" } : { project: null, status: "ready" }, [m, W, S, h]);
169
- return h === null ? i : /* @__PURE__ */ c(te, { registry: y, children: /* @__PURE__ */ c(O, { client: C, children: /* @__PURE__ */ N(
168
+ }, [d.queryClient]), B = F(() => k(null), []), h = d.identityKey, m = w.project, W = typeof m == "object" && m !== null && !Array.isArray(m) && m.use === "default", A = g(() => typeof m == "string" ? { project: m, status: "ready" } : W ? C && C.key === h ? C.state : { project: null, status: "resolving" } : { project: null, status: "ready" }, [m, W, C, h]);
169
+ return h === null ? i : /* @__PURE__ */ l(te, { registry: y, children: /* @__PURE__ */ l(O, { client: E, children: /* @__PURE__ */ N(
170
170
  J,
171
171
  {
172
- baseUrl: E.apiOrigin,
172
+ baseUrl: w.apiOrigin,
173
173
  getSession: U,
174
174
  identityKey: h,
175
175
  ready: r,
176
- project: T.project ?? void 0,
176
+ project: A.project ?? void 0,
177
177
  fetch: u,
178
178
  onUnauthorized: Q,
179
179
  children: [
180
- W ? /* @__PURE__ */ c(
180
+ W ? /* @__PURE__ */ l(
181
181
  Ce,
182
182
  {
183
183
  identityKey: h,
@@ -185,13 +185,13 @@ function Ke({
185
185
  onState: K
186
186
  }
187
187
  ) : null,
188
- /* @__PURE__ */ c(re.Provider, { value: T, children: /* @__PURE__ */ c(
188
+ /* @__PURE__ */ l(re.Provider, { value: A, children: /* @__PURE__ */ l(
189
189
  Ee,
190
190
  {
191
191
  eager: a,
192
- authError: g && g.key === C ? g.error : null,
192
+ authError: S && S.key === E ? S.error : null,
193
193
  onAcquire: B,
194
- children: /* @__PURE__ */ c(we, { children: /* @__PURE__ */ c(ve, { theme: t, children: f }) })
194
+ children: /* @__PURE__ */ l(ge, { children: /* @__PURE__ */ l(we, { theme: t, children: c }) })
195
195
  }
196
196
  ) })
197
197
  ]
@@ -199,9 +199,9 @@ function Ke({
199
199
  ) }, h) });
200
200
  }
201
201
  export {
202
- me as EmbedAuthError,
203
- Ke as W6WEmbedProvider,
204
- Ne as useEmbedProject,
205
- $e as useEmbedStatus
202
+ ye as EmbedAuthError,
203
+ Qe as W6WEmbedProvider,
204
+ Oe as useEmbedProject,
205
+ Ke as useEmbedStatus
206
206
  };
207
207
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":["../src/embed-status.ts","../src/repos/webhook-listen.ts","../src/W6WEmbedProvider.tsx"],"sourcesContent":["/**\n * The embed's public session status, as a pure total function over the `@w6w/react` session\n * store's status plus whether a terminal partner-token 401 has been seen. No React here, so\n * `node:test` covers it exhaustively.\n */\nimport type { W6WSessionStatus } from \"@w6w/react\";\n\nexport type EmbedStatusValue = \"connecting\" | \"ready\" | \"error\";\n\nexport interface EmbedStatus {\n status: EmbedStatusValue;\n /** `EmbedAuthError` for a terminal 401, else the session store's own error; `null` otherwise. */\n error: unknown;\n}\n\n/**\n * The terminal partner-token 401: the host's `getSession` minted a token the API refused, and a\n * renewal did not fix it. `cause` is the SDK `ApiError`.\n */\nexport class EmbedAuthError extends Error {\n constructor(cause: unknown) {\n super(\"The w6w API rejected the embed session token (401).\", { cause });\n this.name = \"EmbedAuthError\";\n }\n}\n\n/**\n * `loading -> connecting`, `ready|renewing -> ready`, `expired -> connecting` (the provider\n * re-acquires), `error -> error`. A seen 401 wins over everything: it is `error` with the\n * `EmbedAuthError`, whatever the store currently says.\n */\nexport function deriveEmbedStatus(\n sessionStatus: W6WSessionStatus,\n sessionError: unknown,\n authError: EmbedAuthError | null,\n): EmbedStatus {\n if (authError) return { status: \"error\", error: authError };\n switch (sessionStatus) {\n case \"ready\":\n case \"renewing\":\n return { status: \"ready\", error: null };\n case \"error\":\n return { status: \"error\", error: sessionError };\n case \"loading\":\n case \"expired\":\n return { status: \"connecting\", error: null };\n }\n}\n","import type { W6WClient } from \"@w6w/sdk\";\nimport { path } from \"@w6w/sdk\";\n/**\n * \"Listen for test event\" on a `@w6w/webhook` subscription — `/subscriptions/:id/listen` over\n * `client.request()`. Not in the SDK's stable contract (Studio reaches it the same way, its\n * `repos/subscriptions.ts`), and `createW6WUiAdapter` carries none of it, so without these the\n * embedded editor's webhook Test tab fell back to the paste-a-payload form.\n */\n\n/**\n * Structural mirror of ui's `WebhookListenSession` (this barrel may not import `@w6w/ui`); the\n * UiBridge assignment typechecks against W6WApi structurally.\n */\nexport interface WebhookListenSession {\n id: string;\n subscriptionId: string;\n nodeId: string | null;\n expiresAt: string;\n status: \"waiting\" | \"captured\" | \"expired\";\n request?: {\n method: string;\n path: string;\n query: Record<string, string>;\n headers: Record<string, string>;\n body: unknown;\n };\n receivedAt?: string;\n}\n\nexport async function startWebhookListen(\n client: W6WClient,\n subscriptionId: string,\n): Promise<{ session: WebhookListenSession; webhookUrl: string }> {\n const res = await client.request<{ session: WebhookListenSession; webhookUrl: string }>({\n method: \"POST\",\n path: path`/subscriptions/${subscriptionId}/listen`,\n body: {},\n });\n return res.body;\n}\n\nexport async function pollWebhookListen(\n client: W6WClient,\n subscriptionId: string,\n sessionId: string,\n opts?: { waitSeconds?: number; signal?: AbortSignal },\n): Promise<WebhookListenSession> {\n const res = await client.request<{ session: WebhookListenSession }>({\n method: \"GET\",\n path: path`/subscriptions/${subscriptionId}/listen/${sessionId}`,\n query: { wait: String(opts?.waitSeconds ?? 0) },\n signal: opts?.signal,\n });\n return res.body.session;\n}\n\nexport async function stopWebhookListen(\n client: W6WClient,\n subscriptionId: string,\n sessionId: string,\n): Promise<void> {\n await client.request<unknown>({\n method: \"DELETE\",\n path: path`/subscriptions/${subscriptionId}/listen/${sessionId}`,\n });\n}\n","import { QueryClient, QueryClientProvider, useQuery } from \"@tanstack/react-query\";\n/**\n * `<W6WEmbedProvider>` — everything an embedded w6w surface needs from a host, behind one\n * element: an identity-scoped `QueryClient`, a `@w6w/react` `<W6WProvider>` (client, session\n * renewal, per-request token) and `@w6w/ui`'s `<W6WUIProvider>` fed by `createW6WUiAdapter`.\n * It composes the three public pieces exactly as `@w6w/react`'s README bridge does: it never\n * spreads or patches the adapter, never reaches into `client.console`, and keeps no session\n * store of its own (`getSession` goes straight to `<W6WProvider>`).\n *\n * **Identity cache.** The `QueryClient` is owned here, not borrowed from the host, and it is a\n * NEW instance whenever `identityKey` changes — so a query cached while signed in as account A\n * is unreachable once the host switches to B. A new client alone is NOT enough: a mounted\n * `useQuery` keeps the `QueryObserver` it was born with, and that observer is bound to the client\n * it was created against, so a child that survives the swap would keep rendering A's cache. The\n * subtree is therefore also re-mounted (`key`), which drops every observer and every piece of\n * child state from the previous identity. The client, the `key` and the tuple handed to\n * `<W6WProvider>` all change in ONE state update: there is no render in which B's tree reads A's\n * cache. The old client is cleared once it is no longer mounted.\n *\n * **Identity switch (flush first).** A draft with a pending save must be written into the account\n * that produced the edit. When `identityKey` changes this provider therefore HOLDS the applied\n * tuple — `identityKey`, `apiOrigin`, `project`, `getSession`, the client — and keeps handing the\n * OLD one to `<W6WProvider>`, awaits `registry.flushAll()` (bounded, never rejects), and only then\n * applies the new tuple in a single update. `<W6WProvider>` swaps its client synchronously on a\n * new `identityKey` and detaches the old session store, so the flush must finish first; and the\n * new `getSession` is NOT forwarded early: `<W6WProvider>` reaches it through the stable wrapper\n * below, whose target is swapped in the same update as the tuple (forwarded early, the new\n * account's token would be minted on the old client). A flush that fails or times out still lets\n * the switch proceed (Q6) and is never retried with the new identity. A token rotation under an\n * unchanged `identityKey` is not a switch: it is forwarded at once, no hold.\n *\n * **No identity.** `identityKey={null}` mounts nothing but `fallback`: no `<W6WProvider>`, no\n * `QueryClientProvider`, no children — so no `getSession` call and no request. `null -> \"A\"`\n * applies at once (nothing can be pending); `\"A\" -> null` takes the SAME flush-first path as any\n * other switch before the fallback renders.\n *\n * **Default project.** `project={{ use: \"default\" }}` resolves ONCE per applied identity, through\n * one `client.projects.list()` query inside the identity-scoped `QueryClient`, to the row with\n * `isDefault === true` — never `list[0]`, never a fallback. `<W6WProvider>` gets no project until\n * it resolves; the client rebuild that follows reuses the cached answer (the query is keyed\n * without the client and lives in a component that stays mounted, so it is not re-issued).\n *\n * **Status.** `useEmbedStatus()` is `deriveEmbedStatus` over the `@w6w/react` session store plus a\n * terminal 401 seen through the forwarded `onUnauthorized`.\n */\nimport {\n W6WProvider,\n type W6WSession,\n createW6WUiAdapter,\n useW6WClient,\n useW6WSession,\n} from \"@w6w/react\";\nimport type { ApiError, FetchLike } from \"@w6w/sdk\";\nimport { type ThemeMode, type W6WApi, W6WUIProvider } from \"@w6w/ui\";\nimport {\n type ReactNode,\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { DraftRegistryProvider, EmbedClientProvider, createDraftRegistry } from \"./draft/index.ts\";\nimport { EmbedAuthError, type EmbedStatus, deriveEmbedStatus } from \"./embed-status.ts\";\nimport {\n EmbedProjectContext,\n type EmbedProjectState,\n useProvidedProject,\n} from \"./project-context.ts\";\nimport { updateConnection } from \"./repos/connections.ts\";\nimport { withCredentialMethods } from \"./repos/credentials.ts\";\nimport { listDataStoreEntries, listDataStores } from \"./repos/data-stores.ts\";\nimport { resolveActionFields } from \"./repos/fields.ts\";\nimport { listModelRoutes } from \"./repos/models.ts\";\nimport {\n pollWebhookListen,\n startWebhookListen,\n stopWebhookListen,\n} from \"./repos/webhook-listen.ts\";\nimport { listNodeSamples, listTestInputs, saveTestInput } from \"./repos/workflows.ts\";\nimport { EmbedThemeContext } from \"./theme-context.ts\";\n\nexport interface W6WEmbedProviderProps {\n /** The w6w API origin, e.g. `\"https://api.w6w.io\"`. */\n apiOrigin: string;\n /**\n * Mints a session for the CURRENT host user (`{token, expiresAt, expiresIn?}`). Always the\n * latest callback; the provider caches and renews the result.\n */\n getSession: () => Promise<W6WSession>;\n /**\n * Which signed-in identity this provider speaks for (e.g. `${userId}:${accountId}`). Changing it\n * rebuilds the API client AND replaces the `QueryClient`, so nothing cached for the previous\n * identity is ever shown under the new one.\n */\n identityKey: string | null;\n /**\n * Rendered instead of the embed while `identityKey` is `null` (no signed-in user). Nothing of\n * the embed mounts then: no `getSession` call, no request. Default `null`.\n */\n fallback?: ReactNode;\n /**\n * Start acquiring a session on mount. Without it the session is acquired lazily, by the first\n * request a mounted surface makes, and `useEmbedStatus()` stays `\"connecting\"` until then.\n */\n eager?: boolean;\n /** Force the `@w6w/ui` theme to follow the host's. Omit to resolve it the library's default way. */\n theme?: ThemeMode;\n /** Gates every read hook while `false` (default `true`) — e.g. until the host has a user. */\n ready?: boolean;\n /**\n * Default project for project-scoped operations: a project id, or `{ use: \"default\" }` to use\n * the account's default project (resolved once per identity; see `useEmbedProject()`).\n */\n project?: string | { use: \"default\" };\n /** Transport override (tests, request recording). Defaults to `globalThis.fetch`. */\n fetch?: FetchLike;\n children: ReactNode;\n}\n\nfunction makeQueryClient(): QueryClient {\n // Same defaults as Studio's own client (`studio/src/main.tsx`).\n return new QueryClient({\n defaultOptions: { queries: { retry: false, refetchOnWindowFocus: false } },\n });\n}\n\n/** The part of the tuple that changes only when a switch has been APPLIED (after the flush). */\ninterface Applied {\n identityKey: string | null;\n queryClient: QueryClient;\n}\n\n/** What `<W6WProvider>` is fed while no switch is in progress; frozen at the last such render. */\ninterface Forwarded {\n apiOrigin: string;\n project: string | { use: \"default\" } | undefined;\n getSession: () => Promise<W6WSession>;\n}\n\n/** Hands the SDK client of the nearest `<W6WProvider>` to `useWorkflowDraft`. */\nfunction ClientBridge({ children }: { children: ReactNode }) {\n return <EmbedClientProvider client={useW6WClient()}>{children}</EmbedClientProvider>;\n}\n\n/** The README bridge: `useW6WClient` -> `createW6WUiAdapter` -> `<W6WUIProvider>`. */\nfunction UiBridge({ theme, children }: { theme?: ThemeMode; children: ReactNode }) {\n const client = useW6WClient();\n const provided = useProvidedProject();\n // `createW6WUiAdapter` has no `updateConnection` or `listModelRoutes`; keep them if it ever\n // gains them, else supply the embed repo's own so the ui Edit modal can save and the\n // `@w6w/model` node's Route field offers the project's routes (not free text) in any host.\n const api = useMemo(() => {\n const adapter: W6WApi = createW6WUiAdapter(client);\n if (typeof adapter.updateConnection !== \"function\") {\n adapter.updateConnection = (id, body) => updateConnection(client, id, body);\n }\n withCredentialMethods(adapter, client);\n if (typeof adapter.listModelRoutes !== \"function\") {\n adapter.listModelRoutes = async (editorProject) => {\n const project = editorProject || provided;\n if (!project) return [];\n const routes = await listModelRoutes(client, project);\n return routes.map((r) => ({ name: r.name, model: r.modelId, status: r.status }));\n };\n }\n // Same for the `@w6w/store` node's store picker: the project's store names, not free text.\n if (typeof adapter.listDataStores !== \"function\") {\n adapter.listDataStores = async (editorProject) => {\n const project = editorProject || provided;\n if (!project) return [];\n return listDataStores(client, project);\n };\n }\n // ...and its key picker: one page of the named store's entries, searched by key prefix.\n if (typeof adapter.listDataStoreEntries !== \"function\") {\n adapter.listDataStoreEntries = async (store, opts) => {\n const project = opts.project || provided;\n if (!project) return { items: [] };\n return listDataStoreEntries(client, project, store, opts);\n };\n }\n // Persisted node samples, so the editor's picker keeps upstream keys across a reload.\n if (typeof adapter.loadNodeSamples !== \"function\") {\n adapter.loadNodeSamples = (workflowId) => listNodeSamples(client, workflowId);\n }\n // Remembered test inputs, so every test form reopens prefilled with the last values used.\n if (typeof adapter.loadTestInputs !== \"function\") {\n adapter.loadTestInputs = (workflowId) => listTestInputs(client, workflowId);\n }\n if (typeof adapter.saveTestInput !== \"function\") {\n adapter.saveTestInput = (workflowId, nodeId, input) =>\n saveTestInput(client, workflowId, nodeId, input);\n }\n if (typeof adapter.resolveActionFields !== \"function\") {\n adapter.resolveActionFields = (appId, actionKey, body, opts) =>\n resolveActionFields(client, appId, actionKey, body, opts);\n }\n // The webhook node's Test tab listens for a real request only when all three exist; without\n // them it falls back to the paste-a-payload form.\n if (typeof adapter.startWebhookListen !== \"function\") {\n adapter.startWebhookListen = (subscriptionId) => startWebhookListen(client, subscriptionId);\n adapter.pollWebhookListen = (subscriptionId, sessionId, opts) =>\n pollWebhookListen(client, subscriptionId, sessionId, opts);\n adapter.stopWebhookListen = (subscriptionId, sessionId) =>\n stopWebhookListen(client, subscriptionId, sessionId);\n }\n return adapter;\n }, [client, provided]);\n return (\n <W6WUIProvider api={api} theme={theme}>\n <EmbedThemeContext.Provider value={theme}>{children}</EmbedThemeContext.Provider>\n </W6WUIProvider>\n );\n}\n\nconst EmbedStatusContext = createContext<EmbedStatus>({ status: \"connecting\", error: null });\n\n/** The session status of the nearest `<W6WEmbedProvider>`. See `deriveEmbedStatus`. */\nexport function useEmbedStatus(): EmbedStatus {\n return useContext(EmbedStatusContext);\n}\n\n/** Publishes `useEmbedStatus()`, and starts the session on mount when `eager`. */\nfunction StatusBridge({\n eager,\n authError,\n onAcquire,\n children,\n}: {\n eager: boolean;\n authError: EmbedAuthError | null;\n onAcquire: () => void;\n children: ReactNode;\n}) {\n const { status, error, refresh } = useW6WSession();\n // `refresh` is per session store, so a rebuilt client (project resolved) is started again.\n useEffect(() => {\n if (eager) void refresh();\n }, [eager, refresh]);\n useEffect(() => {\n if (status === \"loading\" || status === \"renewing\") onAcquire();\n }, [status, onAcquire]);\n const value = useMemo(\n () => deriveEmbedStatus(status, error, authError),\n [status, error, authError],\n );\n return <EmbedStatusContext.Provider value={value}>{children}</EmbedStatusContext.Provider>;\n}\n\n/**\n * Resolves `{use:\"default\"}`. Lives INSIDE `<W6WProvider>` (it needs the client) but at a fixed\n * slot, so it survives the client rebuild that follows resolution; the query key carries no\n * client, so nothing refetches.\n */\nfunction DefaultProjectResolver({\n identityKey,\n enabled,\n onState,\n}: {\n identityKey: string;\n enabled: boolean;\n onState: (key: string, state: EmbedProjectState) => void;\n}) {\n const client = useW6WClient();\n const q = useQuery({\n queryKey: [\"w6w-embed\", \"default-project\"],\n enabled,\n queryFn: async () => {\n const rows = await client.projects.list();\n const home = rows.find((p) => p.isDefault === true);\n if (!home) throw new Error(\"The account has no default project.\");\n return home.id;\n },\n });\n const { isError, error, data } = q;\n const state = useMemo<EmbedProjectState>(\n () =>\n isError\n ? { project: null, status: \"error\", error }\n : data !== undefined\n ? { project: data, status: \"ready\" }\n : { project: null, status: \"resolving\" },\n [isError, error, data],\n );\n useEffect(() => {\n onState(identityKey, state);\n }, [identityKey, state, onState]);\n return null;\n}\n\nexport function W6WEmbedProvider({\n apiOrigin,\n getSession,\n identityKey,\n fallback = null,\n eager = false,\n theme,\n ready,\n project,\n fetch,\n children,\n}: W6WEmbedProviderProps): ReactNode {\n const [registry] = useState(createDraftRegistry);\n const [applied, setApplied] = useState<Applied>(() => ({\n identityKey,\n queryClient: makeQueryClient(),\n }));\n\n // While `identityKey` differs from the applied one a switch is pending: everything below keeps\n // using the values frozen at the last render that was not pending. Otherwise props flow straight\n // through (project / origin changes, token rotation). Idempotent latest-value writes, the same\n // pattern `<W6WProvider>` uses for its own refs.\n const switching = identityKey !== applied.identityKey;\n const forwardedRef = useRef<Forwarded>({ apiOrigin, project, getSession });\n if (!switching) forwardedRef.current = { apiOrigin, project, getSession };\n const forwarded = forwardedRef.current;\n\n // The stable `getSession` handed to `<W6WProvider>`: reads whatever is applied RIGHT NOW. Its\n // target changes in the same render that applies the new tuple, never before the flush settles.\n const sessionRef = useRef(forwarded.getSession);\n sessionRef.current = forwarded.getSession;\n const [stableGetSession] = useState(() => () => sessionRef.current());\n\n useEffect(() => {\n if (identityKey === applied.identityKey) return;\n let cancelled = false;\n const apply = () => {\n if (cancelled) return;\n setApplied({ identityKey, queryClient: makeQueryClient() });\n };\n // Nothing is mounted under a null identity, so nothing can be pending: apply at once.\n if (applied.identityKey === null) {\n apply();\n return () => {\n cancelled = true;\n };\n }\n // `flushAll` never rejects and is bounded; the switch proceeds either way (Q6).\n registry.flushAll().then(apply, apply);\n return () => {\n cancelled = true;\n };\n }, [identityKey, applied.identityKey, registry]);\n\n // The replaced client is dropped once nothing mounted reads it.\n const queryClient = applied.queryClient;\n useEffect(() => () => queryClient.clear(), [queryClient]);\n\n // Default-project resolution, tagged with the identity it was resolved for: a result for A is\n // never read once B is applied.\n const [resolved, setResolved] = useState<{ key: string; state: EmbedProjectState } | null>(null);\n const onResolved = useCallback((key: string, state: EmbedProjectState) => {\n setResolved((prev) =>\n prev &&\n prev.key === key &&\n prev.state.project === state.project &&\n prev.state.status === state.status &&\n prev.state.error === state.error\n ? prev\n : { key, state },\n );\n }, []);\n\n // The terminal partner-token 401, tagged with its identity; cleared when the next acquisition\n // starts (StatusBridge) or the identity changes (the tag no longer matches).\n const [authFailure, setAuthFailure] = useState<{\n key: QueryClient;\n error: EmbedAuthError;\n } | null>(null);\n // The handler is bound to the per-mount client it was created for: a late 401 from a previous\n // `<W6WProvider>` is tagged with ITS client, never the one applied by the time it fires — even\n // when the identity key came back (A -> B -> A mints a new client for the same key).\n const onUnauthorized = useMemo(() => {\n const key = applied.queryClient;\n return (error: ApiError) => {\n setAuthFailure({ key, error: new EmbedAuthError(error) });\n };\n }, [applied.queryClient]);\n const clearAuthFailure = useCallback(() => setAuthFailure(null), []);\n\n const appliedKey = applied.identityKey;\n const spec = forwarded.project;\n // Only exactly `{ use: \"default\" }` asks for the account default; null, `{}`, `[]` or any other\n // object (JS hosts, casts) is \"no project\" and makes no lookup.\n const wantsDefault =\n typeof spec === \"object\" && spec !== null && !Array.isArray(spec) && spec.use === \"default\";\n const projectState: EmbedProjectState = useMemo(() => {\n if (typeof spec === \"string\") return { project: spec, status: \"ready\" };\n if (!wantsDefault) return { project: null, status: \"ready\" };\n return resolved && resolved.key === appliedKey\n ? resolved.state\n : { project: null, status: \"resolving\" };\n }, [spec, wantsDefault, resolved, appliedKey]);\n\n if (appliedKey === null) return fallback;\n\n return (\n <DraftRegistryProvider registry={registry}>\n <QueryClientProvider key={appliedKey} client={queryClient}>\n <W6WProvider\n baseUrl={forwarded.apiOrigin}\n getSession={stableGetSession}\n identityKey={appliedKey}\n ready={ready}\n project={projectState.project ?? undefined}\n fetch={fetch}\n onUnauthorized={onUnauthorized}\n >\n {wantsDefault ? (\n <DefaultProjectResolver\n identityKey={appliedKey}\n enabled={ready !== false}\n onState={onResolved}\n />\n ) : null}\n <EmbedProjectContext.Provider value={projectState}>\n <StatusBridge\n eager={eager}\n authError={authFailure && authFailure.key === queryClient ? authFailure.error : null}\n onAcquire={clearAuthFailure}\n >\n <ClientBridge>\n <UiBridge theme={theme}>{children}</UiBridge>\n </ClientBridge>\n </StatusBridge>\n </EmbedProjectContext.Provider>\n </W6WProvider>\n </QueryClientProvider>\n </DraftRegistryProvider>\n );\n}\n"],"names":["EmbedAuthError","cause","deriveEmbedStatus","sessionStatus","sessionError","authError","startWebhookListen","client","subscriptionId","path","pollWebhookListen","sessionId","opts","stopWebhookListen","makeQueryClient","QueryClient","ClientBridge","children","jsx","EmbedClientProvider","useW6WClient","UiBridge","theme","provided","useProvidedProject","api","useMemo","adapter","createW6WUiAdapter","id","body","updateConnection","withCredentialMethods","editorProject","project","listModelRoutes","r","listDataStores","store","listDataStoreEntries","workflowId","listNodeSamples","listTestInputs","nodeId","input","saveTestInput","appId","actionKey","resolveActionFields","W6WUIProvider","EmbedThemeContext","EmbedStatusContext","createContext","useEmbedStatus","useContext","StatusBridge","eager","onAcquire","status","error","refresh","useW6WSession","useEffect","value","DefaultProjectResolver","identityKey","enabled","onState","q","useQuery","home","p","isError","data","state","W6WEmbedProvider","apiOrigin","getSession","fallback","ready","fetch","registry","useState","createDraftRegistry","applied","setApplied","switching","forwardedRef","useRef","forwarded","sessionRef","stableGetSession","cancelled","apply","queryClient","resolved","setResolved","onResolved","useCallback","key","prev","authFailure","setAuthFailure","onUnauthorized","clearAuthFailure","appliedKey","spec","wantsDefault","projectState","DraftRegistryProvider","QueryClientProvider","jsxs","W6WProvider","EmbedProjectContext"],"mappings":";;;;;;;;;;;;;;;;;;AAmBO,MAAMA,WAAuB,MAAM;AAAA,EACxC,YAAYC,GAAgB;AAC1B,UAAM,uDAAuD,EAAE,OAAAA,GAAO,GACtE,KAAK,OAAO;AAAA,EACd;AACF;AAOO,SAASC,GACdC,GACAC,GACAC,GACa;AACb,MAAIA,EAAW,QAAO,EAAE,QAAQ,SAAS,OAAOA,EAAA;AAChD,UAAQF,GAAA;AAAA,IACN,KAAK;AAAA,IACL,KAAK;AACH,aAAO,EAAE,QAAQ,SAAS,OAAO,KAAA;AAAA,IACnC,KAAK;AACH,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BAACxF,IAAA,EACC,UAAA,gBAAAE,EAACG,IAAA,EAAS,OAAAC,GAAe,UAAAL,GAAS,EAAA,CACpC;AAAA,UAAA;AAAA,QAAA,EACF,CACF;AAAA,MAAA;AAAA,IAAA;AAAA,EAAA,EACF,GA5BwBwF,CA6B1B,GACF;AAEJ;"}
1
+ {"version":3,"file":"index.mjs","sources":["../src/embed-status.ts","../src/repos/webhook-listen.ts","../src/W6WEmbedProvider.tsx"],"sourcesContent":["/**\n * The embed's public session status, as a pure total function over the `@w6w/react` session\n * store's status plus whether a terminal partner-token 401 has been seen. No React here, so\n * `node:test` covers it exhaustively.\n */\nimport type { W6WSessionStatus } from \"@w6w/react\";\n\nexport type EmbedStatusValue = \"connecting\" | \"ready\" | \"error\";\n\nexport interface EmbedStatus {\n status: EmbedStatusValue;\n /** `EmbedAuthError` for a terminal 401, else the session store's own error; `null` otherwise. */\n error: unknown;\n}\n\n/**\n * The terminal partner-token 401: the host's `getSession` minted a token the API refused, and a\n * renewal did not fix it. `cause` is the SDK `ApiError`.\n */\nexport class EmbedAuthError extends Error {\n constructor(cause: unknown) {\n super(\"The w6w API rejected the embed session token (401).\", { cause });\n this.name = \"EmbedAuthError\";\n }\n}\n\n/**\n * `loading -> connecting`, `ready|renewing -> ready`, `expired -> connecting` (the provider\n * re-acquires), `error -> error`. A seen 401 wins over everything: it is `error` with the\n * `EmbedAuthError`, whatever the store currently says.\n */\nexport function deriveEmbedStatus(\n sessionStatus: W6WSessionStatus,\n sessionError: unknown,\n authError: EmbedAuthError | null,\n): EmbedStatus {\n if (authError) return { status: \"error\", error: authError };\n switch (sessionStatus) {\n case \"ready\":\n case \"renewing\":\n return { status: \"ready\", error: null };\n case \"error\":\n return { status: \"error\", error: sessionError };\n case \"loading\":\n case \"expired\":\n return { status: \"connecting\", error: null };\n }\n}\n","import type { W6WClient } from \"@w6w/sdk\";\nimport { path } from \"@w6w/sdk\";\n/**\n * \"Listen for test event\" on a `@w6w/webhook` subscription — `/subscriptions/:id/listen` over\n * `client.request()`. Not in the SDK's stable contract (Studio reaches it the same way, its\n * `repos/subscriptions.ts`), and `createW6WUiAdapter` carries none of it, so without these the\n * embedded editor's webhook Test tab fell back to the paste-a-payload form.\n */\n\n/**\n * Structural mirror of ui's `WebhookListenSession` (this barrel may not import `@w6w/ui`); the\n * UiBridge assignment typechecks against W6WApi structurally.\n */\nexport interface WebhookListenSession {\n id: string;\n subscriptionId: string;\n nodeId: string | null;\n expiresAt: string;\n status: \"waiting\" | \"captured\" | \"expired\";\n request?: {\n method: string;\n path: string;\n query: Record<string, string>;\n headers: Record<string, string>;\n body: unknown;\n };\n receivedAt?: string;\n}\n\nexport async function startWebhookListen(\n client: W6WClient,\n subscriptionId: string,\n): Promise<{ session: WebhookListenSession; webhookUrl: string }> {\n const res = await client.request<{ session: WebhookListenSession; webhookUrl: string }>({\n method: \"POST\",\n path: path`/subscriptions/${subscriptionId}/listen`,\n body: {},\n });\n return res.body;\n}\n\nexport async function pollWebhookListen(\n client: W6WClient,\n subscriptionId: string,\n sessionId: string,\n opts?: { waitSeconds?: number; signal?: AbortSignal },\n): Promise<WebhookListenSession> {\n const res = await client.request<{ session: WebhookListenSession }>({\n method: \"GET\",\n path: path`/subscriptions/${subscriptionId}/listen/${sessionId}`,\n query: { wait: String(opts?.waitSeconds ?? 0) },\n signal: opts?.signal,\n });\n return res.body.session;\n}\n\nexport async function stopWebhookListen(\n client: W6WClient,\n subscriptionId: string,\n sessionId: string,\n): Promise<void> {\n await client.request<unknown>({\n method: \"DELETE\",\n path: path`/subscriptions/${subscriptionId}/listen/${sessionId}`,\n });\n}\n","import { QueryClient, QueryClientProvider, useQuery } from \"@tanstack/react-query\";\n/**\n * `<W6WEmbedProvider>` — everything an embedded w6w surface needs from a host, behind one\n * element: an identity-scoped `QueryClient`, a `@w6w/react` `<W6WProvider>` (client, session\n * renewal, per-request token) and `@w6w/ui`'s `<W6WUIProvider>` fed by `createW6WUiAdapter`.\n * It composes the three public pieces exactly as `@w6w/react`'s README bridge does: it never\n * spreads or patches the adapter, never reaches into `client.console`, and keeps no session\n * store of its own (`getSession` goes straight to `<W6WProvider>`).\n *\n * **Identity cache.** The `QueryClient` is owned here, not borrowed from the host, and it is a\n * NEW instance whenever `identityKey` changes — so a query cached while signed in as account A\n * is unreachable once the host switches to B. A new client alone is NOT enough: a mounted\n * `useQuery` keeps the `QueryObserver` it was born with, and that observer is bound to the client\n * it was created against, so a child that survives the swap would keep rendering A's cache. The\n * subtree is therefore also re-mounted (`key`), which drops every observer and every piece of\n * child state from the previous identity. The client, the `key` and the tuple handed to\n * `<W6WProvider>` all change in ONE state update: there is no render in which B's tree reads A's\n * cache. The old client is cleared once it is no longer mounted.\n *\n * **Identity switch (flush first).** A draft with a pending save must be written into the account\n * that produced the edit. When `identityKey` changes this provider therefore HOLDS the applied\n * tuple — `identityKey`, `apiOrigin`, `project`, `getSession`, the client — and keeps handing the\n * OLD one to `<W6WProvider>`, awaits `registry.flushAll()` (bounded, never rejects), and only then\n * applies the new tuple in a single update. `<W6WProvider>` swaps its client synchronously on a\n * new `identityKey` and detaches the old session store, so the flush must finish first; and the\n * new `getSession` is NOT forwarded early: `<W6WProvider>` reaches it through the stable wrapper\n * below, whose target is swapped in the same update as the tuple (forwarded early, the new\n * account's token would be minted on the old client). A flush that fails or times out still lets\n * the switch proceed (Q6) and is never retried with the new identity. A token rotation under an\n * unchanged `identityKey` is not a switch: it is forwarded at once, no hold.\n *\n * **No identity.** `identityKey={null}` mounts nothing but `fallback`: no `<W6WProvider>`, no\n * `QueryClientProvider`, no children — so no `getSession` call and no request. `null -> \"A\"`\n * applies at once (nothing can be pending); `\"A\" -> null` takes the SAME flush-first path as any\n * other switch before the fallback renders.\n *\n * **Default project.** `project={{ use: \"default\" }}` resolves ONCE per applied identity, through\n * one `client.projects.list()` query inside the identity-scoped `QueryClient`, to the row with\n * `isDefault === true` — never `list[0]`, never a fallback. `<W6WProvider>` gets no project until\n * it resolves; the client rebuild that follows reuses the cached answer (the query is keyed\n * without the client and lives in a component that stays mounted, so it is not re-issued).\n *\n * **Status.** `useEmbedStatus()` is `deriveEmbedStatus` over the `@w6w/react` session store plus a\n * terminal 401 seen through the forwarded `onUnauthorized`.\n */\nimport {\n W6WProvider,\n type W6WSession,\n createW6WUiAdapter,\n useW6WClient,\n useW6WSession,\n} from \"@w6w/react\";\nimport type { ApiError, FetchLike } from \"@w6w/sdk\";\nimport { type ThemeMode, type W6WApi, W6WUIProvider } from \"@w6w/ui\";\nimport {\n type ReactNode,\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { DraftRegistryProvider, EmbedClientProvider, createDraftRegistry } from \"./draft/index.ts\";\nimport { EmbedAuthError, type EmbedStatus, deriveEmbedStatus } from \"./embed-status.ts\";\nimport {\n EmbedProjectContext,\n type EmbedProjectState,\n useProvidedProject,\n} from \"./project-context.ts\";\nimport { updateConnection } from \"./repos/connections.ts\";\nimport { withCredentialMethods } from \"./repos/credentials.ts\";\nimport { listDataStoreEntries, listDataStores } from \"./repos/data-stores.ts\";\nimport { resolveActionFields, resolveTriggerFields } from \"./repos/fields.ts\";\nimport { listModelRoutes } from \"./repos/models.ts\";\nimport {\n pollWebhookListen,\n startWebhookListen,\n stopWebhookListen,\n} from \"./repos/webhook-listen.ts\";\nimport { listNodeSamples, listTestInputs, saveTestInput } from \"./repos/workflows.ts\";\nimport { EmbedThemeContext } from \"./theme-context.ts\";\n\nexport interface W6WEmbedProviderProps {\n /** The w6w API origin, e.g. `\"https://api.w6w.io\"`. */\n apiOrigin: string;\n /**\n * Mints a session for the CURRENT host user (`{token, expiresAt, expiresIn?}`). Always the\n * latest callback; the provider caches and renews the result.\n */\n getSession: () => Promise<W6WSession>;\n /**\n * Which signed-in identity this provider speaks for (e.g. `${userId}:${accountId}`). Changing it\n * rebuilds the API client AND replaces the `QueryClient`, so nothing cached for the previous\n * identity is ever shown under the new one.\n */\n identityKey: string | null;\n /**\n * Rendered instead of the embed while `identityKey` is `null` (no signed-in user). Nothing of\n * the embed mounts then: no `getSession` call, no request. Default `null`.\n */\n fallback?: ReactNode;\n /**\n * Start acquiring a session on mount. Without it the session is acquired lazily, by the first\n * request a mounted surface makes, and `useEmbedStatus()` stays `\"connecting\"` until then.\n */\n eager?: boolean;\n /** Force the `@w6w/ui` theme to follow the host's. Omit to resolve it the library's default way. */\n theme?: ThemeMode;\n /** Gates every read hook while `false` (default `true`) — e.g. until the host has a user. */\n ready?: boolean;\n /**\n * Default project for project-scoped operations: a project id, or `{ use: \"default\" }` to use\n * the account's default project (resolved once per identity; see `useEmbedProject()`).\n */\n project?: string | { use: \"default\" };\n /** Transport override (tests, request recording). Defaults to `globalThis.fetch`. */\n fetch?: FetchLike;\n children: ReactNode;\n}\n\nfunction makeQueryClient(): QueryClient {\n // Same defaults as Studio's own client (`studio/src/main.tsx`).\n return new QueryClient({\n defaultOptions: { queries: { retry: false, refetchOnWindowFocus: false } },\n });\n}\n\n/** The part of the tuple that changes only when a switch has been APPLIED (after the flush). */\ninterface Applied {\n identityKey: string | null;\n queryClient: QueryClient;\n}\n\n/** What `<W6WProvider>` is fed while no switch is in progress; frozen at the last such render. */\ninterface Forwarded {\n apiOrigin: string;\n project: string | { use: \"default\" } | undefined;\n getSession: () => Promise<W6WSession>;\n}\n\n/** Hands the SDK client of the nearest `<W6WProvider>` to `useWorkflowDraft`. */\nfunction ClientBridge({ children }: { children: ReactNode }) {\n return <EmbedClientProvider client={useW6WClient()}>{children}</EmbedClientProvider>;\n}\n\n/** The README bridge: `useW6WClient` -> `createW6WUiAdapter` -> `<W6WUIProvider>`. */\nfunction UiBridge({ theme, children }: { theme?: ThemeMode; children: ReactNode }) {\n const client = useW6WClient();\n const provided = useProvidedProject();\n // `createW6WUiAdapter` has no `updateConnection` or `listModelRoutes`; keep them if it ever\n // gains them, else supply the embed repo's own so the ui Edit modal can save and the\n // `@w6w/model` node's Route field offers the project's routes (not free text) in any host.\n const api = useMemo(() => {\n const adapter: W6WApi = createW6WUiAdapter(client);\n if (typeof adapter.updateConnection !== \"function\") {\n adapter.updateConnection = (id, body) => updateConnection(client, id, body);\n }\n withCredentialMethods(adapter, client);\n if (typeof adapter.listModelRoutes !== \"function\") {\n adapter.listModelRoutes = async (editorProject) => {\n const project = editorProject || provided;\n if (!project) return [];\n const routes = await listModelRoutes(client, project);\n return routes.map((r) => ({ name: r.name, model: r.modelId, status: r.status }));\n };\n }\n // Same for the `@w6w/store` node's store picker: the project's store names, not free text.\n if (typeof adapter.listDataStores !== \"function\") {\n adapter.listDataStores = async (editorProject) => {\n const project = editorProject || provided;\n if (!project) return [];\n return listDataStores(client, project);\n };\n }\n // ...and its key picker: one page of the named store's entries, searched by key prefix.\n if (typeof adapter.listDataStoreEntries !== \"function\") {\n adapter.listDataStoreEntries = async (store, opts) => {\n const project = opts.project || provided;\n if (!project) return { items: [] };\n return listDataStoreEntries(client, project, store, opts);\n };\n }\n // Persisted node samples, so the editor's picker keeps upstream keys across a reload.\n if (typeof adapter.loadNodeSamples !== \"function\") {\n adapter.loadNodeSamples = (workflowId) => listNodeSamples(client, workflowId);\n }\n // Remembered test inputs, so every test form reopens prefilled with the last values used.\n if (typeof adapter.loadTestInputs !== \"function\") {\n adapter.loadTestInputs = (workflowId) => listTestInputs(client, workflowId);\n }\n if (typeof adapter.saveTestInput !== \"function\") {\n adapter.saveTestInput = (workflowId, nodeId, input) =>\n saveTestInput(client, workflowId, nodeId, input);\n }\n if (typeof adapter.resolveActionFields !== \"function\") {\n adapter.resolveActionFields = (appId, actionKey, body, opts) =>\n resolveActionFields(client, appId, actionKey, body, opts);\n }\n if (typeof adapter.resolveTriggerFields !== \"function\") {\n adapter.resolveTriggerFields = (appId, triggerKey, body, opts) =>\n resolveTriggerFields(client, appId, triggerKey, body, opts);\n }\n // The webhook node's Test tab listens for a real request only when all three exist; without\n // them it falls back to the paste-a-payload form.\n if (typeof adapter.startWebhookListen !== \"function\") {\n adapter.startWebhookListen = (subscriptionId) => startWebhookListen(client, subscriptionId);\n adapter.pollWebhookListen = (subscriptionId, sessionId, opts) =>\n pollWebhookListen(client, subscriptionId, sessionId, opts);\n adapter.stopWebhookListen = (subscriptionId, sessionId) =>\n stopWebhookListen(client, subscriptionId, sessionId);\n }\n return adapter;\n }, [client, provided]);\n return (\n <W6WUIProvider api={api} theme={theme}>\n <EmbedThemeContext.Provider value={theme}>{children}</EmbedThemeContext.Provider>\n </W6WUIProvider>\n );\n}\n\nconst EmbedStatusContext = createContext<EmbedStatus>({ status: \"connecting\", error: null });\n\n/** The session status of the nearest `<W6WEmbedProvider>`. See `deriveEmbedStatus`. */\nexport function useEmbedStatus(): EmbedStatus {\n return useContext(EmbedStatusContext);\n}\n\n/** Publishes `useEmbedStatus()`, and starts the session on mount when `eager`. */\nfunction StatusBridge({\n eager,\n authError,\n onAcquire,\n children,\n}: {\n eager: boolean;\n authError: EmbedAuthError | null;\n onAcquire: () => void;\n children: ReactNode;\n}) {\n const { status, error, refresh } = useW6WSession();\n // `refresh` is per session store, so a rebuilt client (project resolved) is started again.\n useEffect(() => {\n if (eager) void refresh();\n }, [eager, refresh]);\n useEffect(() => {\n if (status === \"loading\" || status === \"renewing\") onAcquire();\n }, [status, onAcquire]);\n const value = useMemo(\n () => deriveEmbedStatus(status, error, authError),\n [status, error, authError],\n );\n return <EmbedStatusContext.Provider value={value}>{children}</EmbedStatusContext.Provider>;\n}\n\n/**\n * Resolves `{use:\"default\"}`. Lives INSIDE `<W6WProvider>` (it needs the client) but at a fixed\n * slot, so it survives the client rebuild that follows resolution; the query key carries no\n * client, so nothing refetches.\n */\nfunction DefaultProjectResolver({\n identityKey,\n enabled,\n onState,\n}: {\n identityKey: string;\n enabled: boolean;\n onState: (key: string, state: EmbedProjectState) => void;\n}) {\n const client = useW6WClient();\n const q = useQuery({\n queryKey: [\"w6w-embed\", \"default-project\"],\n enabled,\n queryFn: async () => {\n const rows = await client.projects.list();\n const home = rows.find((p) => p.isDefault === true);\n if (!home) throw new Error(\"The account has no default project.\");\n return home.id;\n },\n });\n const { isError, error, data } = q;\n const state = useMemo<EmbedProjectState>(\n () =>\n isError\n ? { project: null, status: \"error\", error }\n : data !== undefined\n ? { project: data, status: \"ready\" }\n : { project: null, status: \"resolving\" },\n [isError, error, data],\n );\n useEffect(() => {\n onState(identityKey, state);\n }, [identityKey, state, onState]);\n return null;\n}\n\nexport function W6WEmbedProvider({\n apiOrigin,\n getSession,\n identityKey,\n fallback = null,\n eager = false,\n theme,\n ready,\n project,\n fetch,\n children,\n}: W6WEmbedProviderProps): ReactNode {\n const [registry] = useState(createDraftRegistry);\n const [applied, setApplied] = useState<Applied>(() => ({\n identityKey,\n queryClient: makeQueryClient(),\n }));\n\n // While `identityKey` differs from the applied one a switch is pending: everything below keeps\n // using the values frozen at the last render that was not pending. Otherwise props flow straight\n // through (project / origin changes, token rotation). Idempotent latest-value writes, the same\n // pattern `<W6WProvider>` uses for its own refs.\n const switching = identityKey !== applied.identityKey;\n const forwardedRef = useRef<Forwarded>({ apiOrigin, project, getSession });\n if (!switching) forwardedRef.current = { apiOrigin, project, getSession };\n const forwarded = forwardedRef.current;\n\n // The stable `getSession` handed to `<W6WProvider>`: reads whatever is applied RIGHT NOW. Its\n // target changes in the same render that applies the new tuple, never before the flush settles.\n const sessionRef = useRef(forwarded.getSession);\n sessionRef.current = forwarded.getSession;\n const [stableGetSession] = useState(() => () => sessionRef.current());\n\n useEffect(() => {\n if (identityKey === applied.identityKey) return;\n let cancelled = false;\n const apply = () => {\n if (cancelled) return;\n setApplied({ identityKey, queryClient: makeQueryClient() });\n };\n // Nothing is mounted under a null identity, so nothing can be pending: apply at once.\n if (applied.identityKey === null) {\n apply();\n return () => {\n cancelled = true;\n };\n }\n // `flushAll` never rejects and is bounded; the switch proceeds either way (Q6).\n registry.flushAll().then(apply, apply);\n return () => {\n cancelled = true;\n };\n }, [identityKey, applied.identityKey, registry]);\n\n // The replaced client is dropped once nothing mounted reads it.\n const queryClient = applied.queryClient;\n useEffect(() => () => queryClient.clear(), [queryClient]);\n\n // Default-project resolution, tagged with the identity it was resolved for: a result for A is\n // never read once B is applied.\n const [resolved, setResolved] = useState<{ key: string; state: EmbedProjectState } | null>(null);\n const onResolved = useCallback((key: string, state: EmbedProjectState) => {\n setResolved((prev) =>\n prev &&\n prev.key === key &&\n prev.state.project === state.project &&\n prev.state.status === state.status &&\n prev.state.error === state.error\n ? prev\n : { key, state },\n );\n }, []);\n\n // The terminal partner-token 401, tagged with its identity; cleared when the next acquisition\n // starts (StatusBridge) or the identity changes (the tag no longer matches).\n const [authFailure, setAuthFailure] = useState<{\n key: QueryClient;\n error: EmbedAuthError;\n } | null>(null);\n // The handler is bound to the per-mount client it was created for: a late 401 from a previous\n // `<W6WProvider>` is tagged with ITS client, never the one applied by the time it fires — even\n // when the identity key came back (A -> B -> A mints a new client for the same key).\n const onUnauthorized = useMemo(() => {\n const key = applied.queryClient;\n return (error: ApiError) => {\n setAuthFailure({ key, error: new EmbedAuthError(error) });\n };\n }, [applied.queryClient]);\n const clearAuthFailure = useCallback(() => setAuthFailure(null), []);\n\n const appliedKey = applied.identityKey;\n const spec = forwarded.project;\n // Only exactly `{ use: \"default\" }` asks for the account default; null, `{}`, `[]` or any other\n // object (JS hosts, casts) is \"no project\" and makes no lookup.\n const wantsDefault =\n typeof spec === \"object\" && spec !== null && !Array.isArray(spec) && spec.use === \"default\";\n const projectState: EmbedProjectState = useMemo(() => {\n if (typeof spec === \"string\") return { project: spec, status: \"ready\" };\n if (!wantsDefault) return { project: null, status: \"ready\" };\n return resolved && resolved.key === appliedKey\n ? resolved.state\n : { project: null, status: \"resolving\" };\n }, [spec, wantsDefault, resolved, appliedKey]);\n\n if (appliedKey === null) return fallback;\n\n return (\n <DraftRegistryProvider registry={registry}>\n <QueryClientProvider key={appliedKey} client={queryClient}>\n <W6WProvider\n baseUrl={forwarded.apiOrigin}\n getSession={stableGetSession}\n identityKey={appliedKey}\n ready={ready}\n project={projectState.project ?? undefined}\n fetch={fetch}\n onUnauthorized={onUnauthorized}\n >\n {wantsDefault ? (\n <DefaultProjectResolver\n identityKey={appliedKey}\n enabled={ready !== false}\n onState={onResolved}\n />\n ) : null}\n <EmbedProjectContext.Provider value={projectState}>\n <StatusBridge\n eager={eager}\n authError={authFailure && authFailure.key === queryClient ? authFailure.error : null}\n onAcquire={clearAuthFailure}\n >\n <ClientBridge>\n <UiBridge theme={theme}>{children}</UiBridge>\n </ClientBridge>\n </StatusBridge>\n </EmbedProjectContext.Provider>\n </W6WProvider>\n </QueryClientProvider>\n </DraftRegistryProvider>\n );\n}\n"],"names":["EmbedAuthError","cause","deriveEmbedStatus","sessionStatus","sessionError","authError","startWebhookListen","client","subscriptionId","path","pollWebhookListen","sessionId","opts","stopWebhookListen","makeQueryClient","QueryClient","ClientBridge","children","jsx","EmbedClientProvider","useW6WClient","UiBridge","theme","provided","useProvidedProject","api","useMemo","adapter","createW6WUiAdapter","id","body","updateConnection","withCredentialMethods","editorProject","project","listModelRoutes","r","listDataStores","store","listDataStoreEntries","workflowId","listNodeSamples","listTestInputs","nodeId","input","saveTestInput","appId","actionKey","resolveActionFields","triggerKey","resolveTriggerFields","W6WUIProvider","EmbedThemeContext","EmbedStatusContext","createContext","useEmbedStatus","useContext","StatusBridge","eager","onAcquire","status","error","refresh","useW6WSession","useEffect","value","DefaultProjectResolver","identityKey","enabled","onState","q","useQuery","home","p","isError","data","state","W6WEmbedProvider","apiOrigin","getSession","fallback","ready","fetch","registry","useState","createDraftRegistry","applied","setApplied","switching","forwardedRef","useRef","forwarded","sessionRef","stableGetSession","cancelled","apply","queryClient","resolved","setResolved","onResolved","useCallback","key","prev","authFailure","setAuthFailure","onUnauthorized","clearAuthFailure","appliedKey","spec","wantsDefault","projectState","DraftRegistryProvider","QueryClientProvider","jsxs","W6WProvider","EmbedProjectContext"],"mappings":";;;;;;;;;;;;;;;;;;AAmBO,MAAMA,WAAuB,MAAM;AAAA,EACxC,YAAYC,GAAgB;AAC1B,UAAM,uDAAuD,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;AAAA,MACA,gBAAAuB;AAAA,MAEC,UAAA;AAAA,QAAAI,IACC,gBAAA3F;AAAA,UAACgD;AAAA,UAAA;AAAA,YACC,aAAayC;AAAA,YACb,SAAS1B,MAAU;AAAA,YACnB,SAASkB;AAAA,UAAA;AAAA,QAAA,IAET;AAAA,QACJ,gBAAAjF,EAACiG,GAAoB,UAApB,EAA6B,OAAOL,GACnC,UAAA,gBAAA5F;AAAA,UAACuC;AAAA,UAAA;AAAA,YACC,OAAAC;AAAA,YACA,WAAW6C,KAAeA,EAAY,QAAQP,IAAcO,EAAY,QAAQ;AAAA,YAChF,WAAWG;AAAA,YAEX,4BAAC1F,IAAA,EACC,UAAA,gBAAAE,EAACG,IAAA,EAAS,OAAAC,GAAe,UAAAL,GAAS,EAAA,CACpC;AAAA,UAAA;AAAA,QAAA,EACF,CACF;AAAA,MAAA;AAAA,IAAA;AAAA,EAAA,EACF,GA5BwB0F,CA6B1B,GACF;AAEJ;"}
@@ -0,0 +1,26 @@
1
+ import { CallableKind } from './callable-kind.ts';
2
+ /** `name (copy)`, `name (copy 2)`, … — the first one no row in `taken` already shows. */
3
+ export declare function copyDisplayName(name: string, taken: Iterable<string | null | undefined>): string;
4
+ /**
5
+ * `key-copy`, `key-copy-2`, … — the first one not in `taken`, cut so it stays within the key
6
+ * grammar's 39 characters (the cut drops the base's tail, never the suffix, and never leaves a
7
+ * trailing or doubled `-`).
8
+ */
9
+ export declare function copyKey(key: string, taken: Iterable<string | null | undefined>): string;
10
+ /** The siblings a copy must not collide with: their keys and their display names. */
11
+ export interface DuplicateSiblings {
12
+ keys: Iterable<string | null | undefined>;
13
+ names: Iterable<string | null | undefined>;
14
+ }
15
+ /**
16
+ * The definition to POST for a copy of `source` under `newId`. `source` is the kind's editable
17
+ * definition (`callableRecord(...).definition` for a Function/Endpoint, the `workflow` body of a
18
+ * Workflow's `get`) and is never mutated.
19
+ *
20
+ * - `key` — a fresh sibling-free key when the source has one; a Workflow without a key stays
21
+ * without one (its key is optional).
22
+ * - `displayName` — `"<name> (copy)"`, falling back to the key when the source has no name.
23
+ * - Workflow `name` — a blank Workflow's `name` IS its id (`blankDefinition`), so a `name` equal
24
+ * to the old id follows the id; any other `name` is kept.
25
+ */
26
+ export declare function duplicateDefinition(kind: CallableKind, source: Record<string, unknown>, newId: string, siblings: DuplicateSiblings): Record<string, unknown>;
@@ -5,12 +5,12 @@ export type RecentActivityEntry = DashboardStats["recent"][number];
5
5
  /** Human labels for the ledger `kind` domain (mirrors the server's `run_log.kind`). */
6
6
  export declare const KIND_LABELS: Record<string, string>;
7
7
  /**
8
- * The seven ledger kinds this module KNOWS — the arms the two `Record`s below
8
+ * The eight ledger kinds this module KNOWS — the arms the two `Record`s below
9
9
  * name explicitly, so a kind added to `run_log.kind` is a compile error here
10
10
  * rather than a row silently rendering as another kind (the same reasoning
11
11
  * `RESOURCE_DESCRIPTORS` gives for its total `Record`).
12
12
  */
13
- export type ActivityKind = "workflow" | "workflow_step" | "connection_test" | "node_debug" | "function" | "endpoint" | "action";
13
+ export type ActivityKind = "workflow" | "workflow_step" | "connection_test" | "node_debug" | "function" | "endpoint" | "action" | "workflow_adhoc";
14
14
  /**
15
15
  * The label for a ledger kind. An unrecognised kind falls back to the raw value:
16
16
  * `kind` is a wire field and a client can be older than the server that answered
@@ -0,0 +1,6 @@
1
+ /**
2
+ * A one-line preview of a workflow variable's default for the Data rail's read-only list: a
3
+ * literal as itself, an expression with each reference as `{{…}}`, a secret masked. `null` when
4
+ * there is no default.
5
+ */
6
+ export declare function variableDefaultPreview(value: unknown): string | null;