@powerhousedao/switchboard 6.2.3-dev.80 → 6.2.3-dev.81
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.tsbuild/tsconfig.tsbuildinfo +1 -1
- package/CHANGELOG.md +17 -0
- package/dist/index.mjs +1 -1
- package/dist/plugins/attachments.mjs +3 -3
- package/dist/plugins/workflows.mjs +3 -3
- package/dist/{server-eNNf230W.mjs → server-cE1BWLQu.mjs} +5 -5
- package/dist/{server-eNNf230W.mjs.map → server-cE1BWLQu.mjs.map} +1 -1
- package/dist/server.mjs +3 -3
- package/dist/{utils-BbV_nodR.mjs → utils-C6AIF38Z.mjs} +21 -7
- package/dist/utils-C6AIF38Z.mjs.map +1 -0
- package/dist/utils.d.mts.map +1 -1
- package/dist/utils.mjs +3 -3
- package/dist/{workflows-5Chwj98o.mjs → workflows-COM3MKfD.mjs} +33 -36
- package/dist/workflows-COM3MKfD.mjs.map +1 -0
- package/package.json +16 -16
- package/test/default-drive-protocol-versions.test.ts +24 -0
- package/test/goldens/resolvers.json +1 -0
- package/test/goldens/supergraph.graphql +21 -5
- package/test/goldens/workflow-runtime.graphql +21 -5
- package/test/workflow/oauth.test.ts +1 -10
- package/test/workflow/resolvers.test.ts +54 -42
- package/test/workflow/runtime-host.test.ts +4 -5
- package/dist/utils-BbV_nodR.mjs.map +0 -1
- package/dist/workflows-5Chwj98o.mjs.map +0 -1
|
@@ -75,4 +75,28 @@ describe.each([
|
|
|
75
75
|
expect(created[0].header.id).toBe("fixed");
|
|
76
76
|
expect(created[0].header.protocolVersions).toEqual({ "base-reducer": 3 });
|
|
77
77
|
});
|
|
78
|
+
|
|
79
|
+
it("makes a drive anew under its slug when its pinned id is one only a v2 create derives", async () => {
|
|
80
|
+
const { client: reactor, created } = client();
|
|
81
|
+
const errors: string[] = [];
|
|
82
|
+
// The id of a drive created as v2-required in another store
|
|
83
|
+
const pinned = "HRsIHuMMTdmjgCdy9QGWyx96zOFByPo787oBQcEt9f4";
|
|
84
|
+
|
|
85
|
+
const url = await add(
|
|
86
|
+
reactor,
|
|
87
|
+
{ id: pinned, slug: "mail", global: { name: "Mail" } } as never,
|
|
88
|
+
1,
|
|
89
|
+
{ error: (message: string) => errors.push(message) },
|
|
90
|
+
);
|
|
91
|
+
|
|
92
|
+
// Created v2-required under a derived id, not as a legacy one claiming it
|
|
93
|
+
expect(created[0].header.id).not.toBe(pinned);
|
|
94
|
+
expect(created[0].header.protocolVersions).toEqual({
|
|
95
|
+
"base-reducer": 3,
|
|
96
|
+
signature: 2,
|
|
97
|
+
});
|
|
98
|
+
expect(created[0].header.slug).toBe("mail");
|
|
99
|
+
expect(url).toBe("http://localhost:1/d/mail");
|
|
100
|
+
expect(errors[0]).toContain(`pins ${pinned}`);
|
|
101
|
+
});
|
|
78
102
|
});
|
|
@@ -4038,6 +4038,14 @@ input SearchFilterInput {
|
|
|
4038
4038
|
type SecretRecord {
|
|
4039
4039
|
ref: String!
|
|
4040
4040
|
label: String
|
|
4041
|
+
"""
|
|
4042
|
+
The document the secret resolves for; null for a host secret (an OAuth app's).
|
|
4043
|
+
"""
|
|
4044
|
+
ownerId: String
|
|
4045
|
+
"""
|
|
4046
|
+
Whether the caller may rotate or delete it: its creator, able to write its owner.
|
|
4047
|
+
"""
|
|
4048
|
+
manageable: Boolean!
|
|
4041
4049
|
version: Int!
|
|
4042
4050
|
status: String!
|
|
4043
4051
|
createdAt: String!
|
|
@@ -4614,16 +4622,23 @@ type WorkflowRuntimeMutations {
|
|
|
4614
4622
|
"""
|
|
4615
4623
|
rerun(runId: String!): WorkflowRunPayload!
|
|
4616
4624
|
"""
|
|
4617
|
-
Mints a managed secret
|
|
4618
|
-
|
|
4625
|
+
Mints a managed secret for a connection or workflow document and returns
|
|
4626
|
+
its ref; only that document resolves it. The value is stored encrypted
|
|
4627
|
+
and is never readable back over any API.
|
|
4619
4628
|
"""
|
|
4620
|
-
createSecret(
|
|
4629
|
+
createSecret(
|
|
4630
|
+
value: String!
|
|
4631
|
+
label: String
|
|
4632
|
+
documentId: String!
|
|
4633
|
+
): SecretRecord!
|
|
4621
4634
|
"""
|
|
4622
4635
|
Replaces the value behind an existing ref; documents stay untouched.
|
|
4636
|
+
Only its creator, while able to write its owning document.
|
|
4623
4637
|
"""
|
|
4624
4638
|
rotateSecret(ref: String!, value: String!): SecretRecord!
|
|
4625
4639
|
"""
|
|
4626
|
-
Tombstones a secret; its value becomes unrecoverable.
|
|
4640
|
+
Tombstones a secret; its value becomes unrecoverable. Only its creator,
|
|
4641
|
+
while able to write its owning document.
|
|
4627
4642
|
"""
|
|
4628
4643
|
deleteSecret(ref: String!): Boolean!
|
|
4629
4644
|
"""
|
|
@@ -4812,7 +4827,8 @@ type WorkflowRuntimeQueries {
|
|
|
4812
4827
|
"""
|
|
4813
4828
|
webhookEndpoint(workflowId: String!, driveId: String): WebhookEndpointRecord
|
|
4814
4829
|
"""
|
|
4815
|
-
Secret metadata (label, version, status). Never the value.
|
|
4830
|
+
Secret metadata (label, version, status). Never the value. Only secrets
|
|
4831
|
+
whose owning document the caller can read.
|
|
4816
4832
|
"""
|
|
4817
4833
|
secret(ref: String!): SecretRecord
|
|
4818
4834
|
secrets: [SecretRecord!]!
|
|
@@ -605,6 +605,14 @@ type RuntimeHost {
|
|
|
605
605
|
type SecretRecord {
|
|
606
606
|
ref: String!
|
|
607
607
|
label: String
|
|
608
|
+
"""
|
|
609
|
+
The document the secret resolves for; null for a host secret (an OAuth app's).
|
|
610
|
+
"""
|
|
611
|
+
ownerId: String
|
|
612
|
+
"""
|
|
613
|
+
Whether the caller may rotate or delete it: its creator, able to write its owner.
|
|
614
|
+
"""
|
|
615
|
+
manageable: Boolean!
|
|
608
616
|
version: Int!
|
|
609
617
|
status: String!
|
|
610
618
|
createdAt: String!
|
|
@@ -800,16 +808,23 @@ type WorkflowRuntimeMutations {
|
|
|
800
808
|
"""
|
|
801
809
|
rerun(runId: String!): WorkflowRunPayload!
|
|
802
810
|
"""
|
|
803
|
-
Mints a managed secret
|
|
804
|
-
|
|
811
|
+
Mints a managed secret for a connection or workflow document and returns
|
|
812
|
+
its ref; only that document resolves it. The value is stored encrypted
|
|
813
|
+
and is never readable back over any API.
|
|
805
814
|
"""
|
|
806
|
-
createSecret(
|
|
815
|
+
createSecret(
|
|
816
|
+
value: String!
|
|
817
|
+
label: String
|
|
818
|
+
documentId: String!
|
|
819
|
+
): SecretRecord!
|
|
807
820
|
"""
|
|
808
821
|
Replaces the value behind an existing ref; documents stay untouched.
|
|
822
|
+
Only its creator, while able to write its owning document.
|
|
809
823
|
"""
|
|
810
824
|
rotateSecret(ref: String!, value: String!): SecretRecord!
|
|
811
825
|
"""
|
|
812
|
-
Tombstones a secret; its value becomes unrecoverable.
|
|
826
|
+
Tombstones a secret; its value becomes unrecoverable. Only its creator,
|
|
827
|
+
while able to write its owning document.
|
|
813
828
|
"""
|
|
814
829
|
deleteSecret(ref: String!): Boolean!
|
|
815
830
|
"""
|
|
@@ -998,7 +1013,8 @@ type WorkflowRuntimeQueries {
|
|
|
998
1013
|
"""
|
|
999
1014
|
webhookEndpoint(workflowId: String!, driveId: String): WebhookEndpointRecord
|
|
1000
1015
|
"""
|
|
1001
|
-
Secret metadata (label, version, status). Never the value.
|
|
1016
|
+
Secret metadata (label, version, status). Never the value. Only secrets
|
|
1017
|
+
whose owning document the caller can read.
|
|
1002
1018
|
"""
|
|
1003
1019
|
secret(ref: String!): SecretRecord
|
|
1004
1020
|
secrets: [SecretRecord!]!
|
|
@@ -4,7 +4,6 @@ import {
|
|
|
4
4
|
createHttpAdapter,
|
|
5
5
|
HttpRouteService,
|
|
6
6
|
type Context,
|
|
7
|
-
type IAuthorizationService,
|
|
8
7
|
} from "@powerhousedao/reactor-api";
|
|
9
8
|
import type { WorkflowRuntimeService } from "@powerhousedao/reactor-workflow";
|
|
10
9
|
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
|
@@ -115,13 +114,12 @@ describe("startOAuth", () => {
|
|
|
115
114
|
user: { address: "0xadmin" },
|
|
116
115
|
}) as unknown as Context;
|
|
117
116
|
|
|
118
|
-
function build(callbackUrl: string | undefined
|
|
117
|
+
function build(callbackUrl: string | undefined) {
|
|
119
118
|
const runtime = {
|
|
120
119
|
startOAuth: vi.fn(() => Promise.resolve({})),
|
|
121
120
|
};
|
|
122
121
|
const resolvers = getResolvers(
|
|
123
122
|
runtime as unknown as WorkflowRuntimeService,
|
|
124
|
-
{ isSupremeAdmin: () => isAdmin } as unknown as IAuthorizationService,
|
|
125
123
|
callbackUrl ? { callbackUrl } : undefined,
|
|
126
124
|
) as Record<string, Record<string, Resolver>>;
|
|
127
125
|
return {
|
|
@@ -133,13 +131,6 @@ describe("startOAuth", () => {
|
|
|
133
131
|
|
|
134
132
|
const PATH = "/api/@powerhousedao/workflow/oauth/callback";
|
|
135
133
|
|
|
136
|
-
it("is an administrator's, like minting a secret", () => {
|
|
137
|
-
const { start } = build(`https://sb.example${PATH}`, false);
|
|
138
|
-
expect(() => start({}, { connectionId: "c1" }, ctx())).toThrow(
|
|
139
|
-
"Admin access required",
|
|
140
|
-
);
|
|
141
|
-
});
|
|
142
|
-
|
|
143
134
|
it("uses the host's own redirect when it knows its origin", async () => {
|
|
144
135
|
const { runtime, start } = build(`https://sb.example${PATH}`);
|
|
145
136
|
await start(
|
|
@@ -1,9 +1,7 @@
|
|
|
1
1
|
// What the workflow subgraph does with the caller behind a request: every
|
|
2
|
-
// workflow-scoped field hands it to the runtime,
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
IAuthorizationService,
|
|
6
|
-
} from "@powerhousedao/reactor-api";
|
|
2
|
+
// workflow-scoped field, secrets included, hands it to the runtime, which
|
|
3
|
+
// gates secrets on their owner document and creator rather than on admin.
|
|
4
|
+
import type { Context } from "@powerhousedao/reactor-api";
|
|
7
5
|
import {
|
|
8
6
|
WORKFLOW_SYNCING_MESSAGE,
|
|
9
7
|
WorkflowSyncingError,
|
|
@@ -54,24 +52,20 @@ function fakeRuntime() {
|
|
|
54
52
|
reactorAccessDenial: vi.fn((): string | undefined => undefined),
|
|
55
53
|
testTrigger: vi.fn(() => Promise.resolve(null)),
|
|
56
54
|
cancelTriggerTestFor: vi.fn(() => Promise.resolve(true)),
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
),
|
|
55
|
+
createSecret: vi.fn(() => Promise.resolve({ ref: "secret://v1:00" })),
|
|
56
|
+
rotateSecret: vi.fn(() => Promise.resolve({ ref: "secret://v1:00" })),
|
|
57
|
+
deleteSecret: vi.fn(() => Promise.resolve()),
|
|
58
|
+
secretStat: vi.fn(() => Promise.resolve(null)),
|
|
59
|
+
listSecrets: vi.fn(() => Promise.resolve([])),
|
|
60
|
+
canManageSecret: vi.fn(() => Promise.resolve(false)),
|
|
61
|
+
secrets: vi.fn(),
|
|
64
62
|
};
|
|
65
63
|
}
|
|
66
64
|
|
|
67
|
-
function build(
|
|
65
|
+
function build() {
|
|
68
66
|
const runtime = fakeRuntime();
|
|
69
|
-
const authorizationService = {
|
|
70
|
-
isSupremeAdmin: vi.fn(() => isAdmin),
|
|
71
|
-
} as unknown as IAuthorizationService;
|
|
72
67
|
const resolvers = getResolvers(
|
|
73
68
|
runtime as unknown as WorkflowRuntimeService,
|
|
74
|
-
authorizationService,
|
|
75
69
|
undefined,
|
|
76
70
|
undefined,
|
|
77
71
|
(documentId) =>
|
|
@@ -83,12 +77,13 @@ function build(isAdmin: boolean) {
|
|
|
83
77
|
runtime,
|
|
84
78
|
queries: resolvers.WorkflowRuntimeQueries,
|
|
85
79
|
mutations: resolvers.WorkflowRuntimeMutations,
|
|
80
|
+
secretRecord: resolvers.SecretRecord,
|
|
86
81
|
};
|
|
87
82
|
}
|
|
88
83
|
|
|
89
84
|
describe("the workflow resolvers and the caller", () => {
|
|
90
85
|
it("hands the caller to every workflow-scoped field", async () => {
|
|
91
|
-
const { runtime, queries, mutations } = build(
|
|
86
|
+
const { runtime, queries, mutations } = build();
|
|
92
87
|
|
|
93
88
|
await queries.webhookEndpoint({}, { workflowId: "wf-1" }, CTX);
|
|
94
89
|
await queries.triggerStates({}, {}, CTX);
|
|
@@ -132,7 +127,7 @@ describe("the workflow resolvers and the caller", () => {
|
|
|
132
127
|
});
|
|
133
128
|
|
|
134
129
|
it("passes the caller's drive, and tags a still-syncing workflow", async () => {
|
|
135
|
-
const { runtime, queries, mutations } = build(
|
|
130
|
+
const { runtime, queries, mutations } = build();
|
|
136
131
|
const drive = { driveId: "drive-1" };
|
|
137
132
|
|
|
138
133
|
await queries.webhookEndpoint({}, { workflowId: "wf-1", ...drive }, CTX);
|
|
@@ -153,32 +148,49 @@ describe("the workflow resolvers and the caller", () => {
|
|
|
153
148
|
expect(runtime.testStep).toHaveBeenCalledWith("wf-1", "s1", CTX, drive);
|
|
154
149
|
});
|
|
155
150
|
|
|
156
|
-
it("
|
|
157
|
-
const { runtime, mutations } = build(
|
|
151
|
+
it("hands every secret field to the runtime with the caller, never the store", async () => {
|
|
152
|
+
const { runtime, queries, mutations, secretRecord } = build();
|
|
153
|
+
const stat = { ref: "secret://v1:00", ownerId: "conn-1" };
|
|
158
154
|
|
|
155
|
+
await mutations.createSecret(
|
|
156
|
+
{},
|
|
157
|
+
{ value: "s3cret", documentId: "conn-1" },
|
|
158
|
+
CTX,
|
|
159
|
+
);
|
|
160
|
+
await mutations.rotateSecret({}, { ref: stat.ref, value: "s" }, CTX);
|
|
159
161
|
await expect(
|
|
160
|
-
mutations.
|
|
161
|
-
).
|
|
162
|
-
await
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
162
|
+
mutations.deleteSecret({}, { ref: stat.ref }, CTX),
|
|
163
|
+
).resolves.toBe(true);
|
|
164
|
+
await queries.secret({}, { ref: stat.ref }, CTX);
|
|
165
|
+
await queries.secrets({}, {}, CTX);
|
|
166
|
+
await secretRecord.manageable(stat, {}, CTX);
|
|
167
|
+
|
|
168
|
+
expect(runtime.createSecret).toHaveBeenCalledWith(
|
|
169
|
+
{ value: "s3cret", label: undefined, ownerId: "conn-1" },
|
|
170
|
+
CTX,
|
|
171
|
+
);
|
|
172
|
+
expect(runtime.rotateSecret).toHaveBeenCalledWith(stat.ref, "s", CTX);
|
|
173
|
+
expect(runtime.deleteSecret).toHaveBeenCalledWith(stat.ref, CTX);
|
|
174
|
+
expect(runtime.secretStat).toHaveBeenCalledWith(stat.ref, CTX);
|
|
175
|
+
expect(runtime.listSecrets).toHaveBeenCalledWith(CTX);
|
|
176
|
+
expect(runtime.canManageSecret).toHaveBeenCalledWith(stat, CTX);
|
|
177
|
+
// Nothing reaches the raw store, whose get returns values.
|
|
169
178
|
expect(runtime.secrets).not.toHaveBeenCalled();
|
|
170
179
|
});
|
|
171
180
|
|
|
172
|
-
it("
|
|
173
|
-
const { runtime, mutations } = build(
|
|
174
|
-
|
|
175
|
-
await mutations.createSecret({}, { value: "s3cret", label: "slack" }, CTX);
|
|
181
|
+
it("tags a secret minted for a document still syncing", async () => {
|
|
182
|
+
const { runtime, mutations } = build();
|
|
183
|
+
runtime.createSecret.mockRejectedValueOnce(new WorkflowSyncingError());
|
|
176
184
|
|
|
177
|
-
expect(
|
|
185
|
+
await expect(
|
|
186
|
+
mutations.createSecret({}, { value: "s", documentId: "c1" }, CTX),
|
|
187
|
+
).rejects.toMatchObject({
|
|
188
|
+
extensions: { code: "WORKFLOW_SYNCING", retryable: true },
|
|
189
|
+
});
|
|
178
190
|
});
|
|
179
191
|
|
|
180
192
|
it("serves why a workflow got no reactor access, naming the publisher", async () => {
|
|
181
|
-
const { runtime, queries } = build(
|
|
193
|
+
const { runtime, queries } = build();
|
|
182
194
|
runtime.reactorAccessDenial.mockReturnValueOnce(
|
|
183
195
|
'The publisher 0xabc cannot read reactor connection "conn-1"',
|
|
184
196
|
);
|
|
@@ -197,7 +209,7 @@ describe("the workflow resolvers and the caller", () => {
|
|
|
197
209
|
});
|
|
198
210
|
|
|
199
211
|
it("serves the piece version a run's steps ran", async () => {
|
|
200
|
-
const { runtime, queries } = build(
|
|
212
|
+
const { runtime, queries } = build();
|
|
201
213
|
runtime.run.mockResolvedValueOnce({
|
|
202
214
|
row: { id: "run-1", warnings: 1, trigger_payload: null },
|
|
203
215
|
steps: [
|
|
@@ -231,7 +243,7 @@ describe("the workflow resolvers and the caller", () => {
|
|
|
231
243
|
|
|
232
244
|
describe("the runs listing and step data", () => {
|
|
233
245
|
it("reads step blobs only when the query selects them", async () => {
|
|
234
|
-
const { runtime, queries } = build(
|
|
246
|
+
const { runtime, queries } = build();
|
|
235
247
|
const withData = (query: string) =>
|
|
236
248
|
queries.runs({}, {}, CTX, runsInfo(query)).then(
|
|
237
249
|
() =>
|
|
@@ -271,7 +283,7 @@ describe("the runs listing and step data", () => {
|
|
|
271
283
|
|
|
272
284
|
describe("the runs page", () => {
|
|
273
285
|
it("passes paging through and serves the page", async () => {
|
|
274
|
-
const { runtime, queries } = build(
|
|
286
|
+
const { runtime, queries } = build();
|
|
275
287
|
runtime.runsPage.mockResolvedValueOnce({
|
|
276
288
|
records: [],
|
|
277
289
|
hasNextPage: true,
|
|
@@ -310,7 +322,7 @@ describe("the runs page", () => {
|
|
|
310
322
|
});
|
|
311
323
|
|
|
312
324
|
it("reports a cursor it did not issue as bad input", async () => {
|
|
313
|
-
const { runtime, queries } = build(
|
|
325
|
+
const { runtime, queries } = build();
|
|
314
326
|
const invalid = new Error("Invalid runs cursor");
|
|
315
327
|
invalid.name = "InvalidRunCursorError";
|
|
316
328
|
runtime.runsPage.mockRejectedValueOnce(invalid);
|
|
@@ -326,7 +338,7 @@ describe("the runs page", () => {
|
|
|
326
338
|
|
|
327
339
|
describe("piece search", () => {
|
|
328
340
|
it("passes a valid filter through", async () => {
|
|
329
|
-
const { runtime, queries } = build(
|
|
341
|
+
const { runtime, queries } = build();
|
|
330
342
|
await queries.searchPieces(
|
|
331
343
|
{},
|
|
332
344
|
{ query: "send", kind: "trigger", sources: ["registry", "local"] },
|
|
@@ -341,7 +353,7 @@ describe("piece search", () => {
|
|
|
341
353
|
});
|
|
342
354
|
|
|
343
355
|
it("refuses a kind or source it does not know, rather than widen", () => {
|
|
344
|
-
const { runtime, queries } = build(
|
|
356
|
+
const { runtime, queries } = build();
|
|
345
357
|
expect(() =>
|
|
346
358
|
queries.searchPieces({}, { query: "send", kind: "triggers" }, CTX),
|
|
347
359
|
).toThrow(/kind is "action" or "trigger"/);
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import type { IAuthorizationService } from "@powerhousedao/reactor-api";
|
|
2
1
|
import type { WorkflowRuntimeService } from "@powerhousedao/reactor-workflow";
|
|
3
2
|
import { hostname } from "node:os";
|
|
4
3
|
import { describe, expect, it } from "vitest";
|
|
@@ -8,10 +7,10 @@ type Resolver = (...args: unknown[]) => unknown;
|
|
|
8
7
|
|
|
9
8
|
describe("the runtime's host", () => {
|
|
10
9
|
it("is the switchboard on this machine, the id apps record as runner", () => {
|
|
11
|
-
const resolvers = getResolvers(
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
10
|
+
const resolvers = getResolvers({} as WorkflowRuntimeService) as Record<
|
|
11
|
+
string,
|
|
12
|
+
Record<string, Resolver>
|
|
13
|
+
>;
|
|
15
14
|
expect(resolvers.WorkflowRuntimeQueries.host()).toEqual({
|
|
16
15
|
id: `switchboard@${hostname()}`,
|
|
17
16
|
label: hostname(),
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"utils-BbV_nodR.mjs","sources":["../src/utils.mts"],"sourcesContent":["import type { IReactorClient } from \"@powerhousedao/reactor\";\nimport {\n REACTOR_DRIVE_DOCUMENT_TYPE,\n reactorDriveCreateState,\n} from \"@powerhousedao/reactor-drive\";\nimport {\n driveCreateState,\n driveDocumentType,\n} from \"@powerhousedao/shared/document-drive\";\nimport type { DriveInput } from \"@powerhousedao/shared/document-drive\";\nimport type {\n PHBaseState,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\n\n/**\n * A configured id pins the drive, and only a legacy drive can take a chosen\n * id; otherwise the client's creation default applies.\n */\nfunction newDrive<TDocument extends PHDocument>(\n client: IReactorClient,\n documentType: string,\n initialState: Partial<PHBaseState>,\n id: string | undefined,\n): Promise<TDocument> {\n return client.newDocument<TDocument>(documentType, {\n initialState,\n ...(id ? { signaturePolicy: \"legacy\" as const, id } : {}),\n });\n}\n\ntype DefaultDriveLogger = { error: (message: string) => void };\n\n/** The document that already holds `slug`; null when two do (an id and a slug). */\nasync function slugHolder(\n client: IReactorClient,\n slug: string,\n): Promise<PHDocument | null | undefined> {\n let id: string;\n try {\n id = await client.resolveIdOrSlug(slug);\n } catch (error) {\n const notFound =\n error instanceof Error && error.name === \"DocumentNotFoundError\";\n return notFound ? undefined : null;\n }\n return client.get(id);\n}\n\n/**\n * A default drive whose slug another document holds: a drive of the same type\n * stands in for it (its URL); anything else keeps it uncreated (null), with an\n * error logged so the server still starts. Undefined when the slug is free.\n */\nasync function slugTakenBy(\n client: IReactorClient,\n drive: DriveInput,\n documentType: string,\n serverPort: number,\n logger: DefaultDriveLogger,\n): Promise<string | null | undefined> {\n if (!drive.slug) return undefined;\n const holder = await slugHolder(client, drive.slug);\n if (holder === undefined) return undefined;\n if (holder?.header.documentType === documentType) {\n return `http://localhost:${serverPort}/d/${holder.header.id}`;\n }\n const owner = holder\n ? `${holder.header.documentType} document ${holder.header.id}`\n : \"two documents\";\n logger.error(\n `The default drive \"${drive.slug}\" was not created: the slug belongs to ${owner}.`,\n );\n return null;\n}\n\n/** Creates a configured drive unless one with its id or slug exists; the\n * URL it is served at, or undefined when another document holds the slug. */\nexport async function addDefaultDrive(\n client: IReactorClient,\n drive: DriveInput,\n serverPort: number,\n logger: DefaultDriveLogger = console,\n): Promise<string | undefined> {\n let driveId = drive.id;\n if (!driveId || driveId.length === 0) {\n driveId = drive.slug;\n }\n\n if (!driveId || driveId.length === 0) {\n throw new Error(\"Invalid Drive Id\");\n }\n\n // check if the drive already exists\n let existingDrive;\n try {\n existingDrive = await client.get(driveId);\n } catch {\n //\n }\n\n // already exists, return the existing drive url\n if (existingDrive) {\n return `http://localhost:${serverPort}/d/${driveId}`;\n }\n\n const { global } = driveCreateState();\n const taken = await slugTakenBy(\n client,\n drive,\n driveDocumentType,\n serverPort,\n logger,\n );\n if (taken !== undefined) return taken ?? undefined;\n\n const document = await newDrive(\n client,\n driveDocumentType,\n {\n global: {\n ...global,\n name: drive.global.name,\n icon: drive.global.icon ?? global.icon,\n },\n local: {\n availableOffline: drive.local?.availableOffline ?? false,\n sharingType: drive.local?.sharingType ?? \"public\",\n listeners: drive.local?.listeners ?? [],\n triggers: drive.local?.triggers ?? [],\n },\n } as Partial<PHBaseState>,\n drive.id,\n );\n if (drive.slug && drive.slug.length > 0) {\n document.header.slug = drive.slug;\n }\n if (drive.global.name) {\n document.header.name = drive.global.name;\n }\n if (drive.preferredEditor) {\n document.header.meta = { preferredEditor: drive.preferredEditor };\n }\n\n try {\n await (\n await client.write.create(document)\n ).readable;\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : String(e);\n if (!errorMessage.includes(\"already exists\")) {\n throw e;\n }\n }\n\n return `http://localhost:${serverPort}/d/${driveId}`;\n}\n\n/** addDefaultDrive for a reactor drive. */\nexport async function addDefaultReactorDrive(\n client: IReactorClient,\n drive: DriveInput,\n serverPort: number,\n logger: DefaultDriveLogger = console,\n): Promise<string | undefined> {\n let driveId = drive.id;\n if (!driveId || driveId.length === 0) {\n driveId = drive.slug;\n }\n\n if (!driveId || driveId.length === 0) {\n throw new Error(\"Invalid Drive Id\");\n }\n\n let existingDrive;\n try {\n existingDrive = await client.get(driveId);\n } catch {\n //\n }\n\n if (existingDrive) {\n return `http://localhost:${serverPort}/d/${driveId}`;\n }\n\n const { global, local } = reactorDriveCreateState();\n const taken = await slugTakenBy(\n client,\n drive,\n REACTOR_DRIVE_DOCUMENT_TYPE,\n serverPort,\n logger,\n );\n if (taken !== undefined) return taken ?? undefined;\n\n const document = await newDrive(\n client,\n REACTOR_DRIVE_DOCUMENT_TYPE,\n {\n global: {\n ...global,\n name: drive.global.name,\n icon: drive.global.icon ?? global.icon,\n },\n local: {\n ...local,\n availableOffline:\n drive.local?.availableOffline ?? local.availableOffline,\n sharingType: drive.local?.sharingType ?? local.sharingType,\n },\n } as Partial<PHBaseState>,\n drive.id,\n );\n if (drive.slug && drive.slug.length > 0) {\n document.header.slug = drive.slug;\n }\n if (drive.global.name) {\n document.header.name = drive.global.name;\n }\n if (drive.preferredEditor) {\n document.header.meta = { preferredEditor: drive.preferredEditor };\n }\n\n try {\n await (\n await client.write.create(document)\n ).readable;\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : String(e);\n if (!errorMessage.includes(\"already exists\")) {\n throw e;\n }\n }\n\n return `http://localhost:${serverPort}/d/${driveId}`;\n}\n\nexport { isPostgresUrl } from \"./postgres-url.mjs\";\n"],"names":[],"mappings":";;;;;;;;;AAmBA,SAAS,SACP,QACA,cACA,cACA,IACoB;CACpB,OAAO,OAAO,YAAuB,cAAc;EACjD;EACA,GAAI,KAAK;GAAE,iBAAiB;GAAmB;EAAG,IAAI,CAAC;CACzD,CAAC;AACH;;AAKA,eAAe,WACb,QACA,MACwC;CACxC,IAAI;CACJ,IAAI;EACF,KAAK,MAAM,OAAO,gBAAgB,IAAI;CACxC,SAAS,OAAO;EAGd,OADE,iBAAiB,SAAS,MAAM,SAAS,0BACzB,KAAA,IAAY;CAChC;CACA,OAAO,OAAO,IAAI,EAAE;AACtB;;;;;;AAOA,eAAe,YACb,QACA,OACA,cACA,YACA,QACoC;CACpC,IAAI,CAAC,MAAM,MAAM,OAAO,KAAA;CACxB,MAAM,SAAS,MAAM,WAAW,QAAQ,MAAM,IAAI;CAClD,IAAI,WAAW,KAAA,GAAW,OAAO,KAAA;CACjC,IAAI,QAAQ,OAAO,iBAAiB,cAClC,OAAO,oBAAoB,WAAW,KAAK,OAAO,OAAO;CAE3D,MAAM,QAAQ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