@dads-framework/toolbox 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +50 -5
- package/bin/usage.js +13 -0
- package/dist/cli-db-commands.d.ts +43 -0
- package/dist/cli-db-commands.d.ts.map +1 -0
- package/dist/cli-db-commands.js +276 -0
- package/dist/cli-db-commands.js.map +1 -0
- package/dist/cli-db-loader.d.ts +82 -0
- package/dist/cli-db-loader.d.ts.map +1 -0
- package/dist/cli-db-loader.js +142 -0
- package/dist/cli-db-loader.js.map +1 -0
- package/dist/cli-migrate-commands.d.ts.map +1 -1
- package/dist/cli-migrate-commands.js +3 -1
- package/dist/cli-migrate-commands.js.map +1 -1
- package/dist/cli.js +4 -0
- package/dist/cli.js.map +1 -1
- package/dist/doctor/issue-catalog-enforcement.d.ts.map +1 -1
- package/dist/doctor/issue-catalog-enforcement.js +4 -0
- package/dist/doctor/issue-catalog-enforcement.js.map +1 -1
- package/dist/doctor/signals/its-not-you-its-my-boundaries/cross-domain-foreign-keys.d.ts +15 -0
- package/dist/doctor/signals/its-not-you-its-my-boundaries/cross-domain-foreign-keys.d.ts.map +1 -0
- package/dist/doctor/signals/its-not-you-its-my-boundaries/cross-domain-foreign-keys.js +188 -0
- package/dist/doctor/signals/its-not-you-its-my-boundaries/cross-domain-foreign-keys.js.map +1 -0
- package/dist/doctor/signals/registry/text-and-packages.d.ts.map +1 -1
- package/dist/doctor/signals/registry/text-and-packages.js +2 -0
- package/dist/doctor/signals/registry/text-and-packages.js.map +1 -1
- package/dist/migrate-v03.d.ts +1 -1
- package/dist/migrate-v03.d.ts.map +1 -1
- package/dist/resource-generators/domain-generator.d.ts.map +1 -1
- package/dist/resource-generators/domain-generator.js +51 -9
- package/dist/resource-generators/domain-generator.js.map +1 -1
- package/dist/starter-project/kit-starter.generated.d.ts.map +1 -1
- package/dist/starter-project/kit-starter.generated.js +16 -15
- package/dist/starter-project/kit-starter.generated.js.map +1 -1
- package/dist/toolbox.tsbuildinfo +1 -1
- package/package.json +3 -3
|
@@ -12,21 +12,42 @@ export function ensureDomain(plan, domain) {
|
|
|
12
12
|
plan.create(`${directory}/README.md`, `# ${domain}\n\nDomain-owned pure logic, contracts, access rules, server adapters, and web clients. An API must explicitly select this domain in its app entry point.\n`);
|
|
13
13
|
plan.create(`${directory}/pure/${item}.ts`, pureCore(item));
|
|
14
14
|
plan.create(`${directory}/pure/${item}.test.ts`, pureCoreTest(item));
|
|
15
|
-
plan.create(`${directory}/contract/index.ts`,
|
|
15
|
+
plan.create(`${directory}/contract/index.ts`, contractModule(item));
|
|
16
16
|
plan.create(`${directory}/web-client/index.ts`, "export {};\n");
|
|
17
|
-
plan.create(`${directory}/access/index.ts`, accessRegistry());
|
|
17
|
+
plan.create(`${directory}/access/index.ts`, accessRegistry(item));
|
|
18
18
|
plan.create(`${directory}/server/flags.ts`, `import type { FeatureFlagDefinition } from "@dads-framework/feature-flags";\n\n// dad:add imports\n\nexport const featureFlags: FeatureFlagDefinition[] = [\n // dad:add flags\n];\n`);
|
|
19
19
|
plan.create(`${directory}/server/routes.ts`, routeRegistry());
|
|
20
20
|
plan.create(`${directory}/server/plugin.ts`, domainPlugin(domain));
|
|
21
21
|
}
|
|
22
|
+
function contractModule(item) {
|
|
23
|
+
const itemCamel = camel(item);
|
|
24
|
+
const typeName = pascal(item);
|
|
25
|
+
const label = title(item);
|
|
26
|
+
return `import { entityIdSchema } from "@dads-framework/core/contract";
|
|
27
|
+
import { z } from "zod";
|
|
28
|
+
|
|
29
|
+
export const ${itemCamel}IdSchema = entityIdSchema("${typeName}Id", "${label} identifier.");
|
|
30
|
+
export type ${typeName}Id = z.infer<typeof ${itemCamel}IdSchema>;
|
|
31
|
+
|
|
32
|
+
export const ${itemCamel}WireSchema = z.strictObject({
|
|
33
|
+
id: ${itemCamel}IdSchema,
|
|
34
|
+
title: z.string().trim().min(1),
|
|
35
|
+
});
|
|
36
|
+
export type ${typeName}Wire = z.infer<typeof ${itemCamel}WireSchema>;
|
|
37
|
+
`;
|
|
38
|
+
}
|
|
22
39
|
function pureCore(item) {
|
|
23
40
|
const typeName = pascal(item);
|
|
24
41
|
const label = title(item);
|
|
25
|
-
return `
|
|
42
|
+
return `import type { ${typeName}Id } from "../contract/index.js";
|
|
43
|
+
|
|
44
|
+
export type ${typeName}Draft = {
|
|
45
|
+
readonly id: ${typeName}Id;
|
|
26
46
|
readonly title: string;
|
|
27
47
|
};
|
|
28
48
|
|
|
29
49
|
export type Normalized${typeName} = {
|
|
50
|
+
readonly id: ${typeName}Id;
|
|
30
51
|
readonly title: string;
|
|
31
52
|
};
|
|
32
53
|
|
|
@@ -35,36 +56,57 @@ export function normalize${typeName}(input: ${typeName}Draft): Normalized${typeN
|
|
|
35
56
|
if (normalizedTitle.length === 0) {
|
|
36
57
|
throw new Error("${label} title cannot be empty.");
|
|
37
58
|
}
|
|
38
|
-
return { title: normalizedTitle };
|
|
59
|
+
return { id: input.id, title: normalizedTitle };
|
|
39
60
|
}
|
|
40
61
|
`;
|
|
41
62
|
}
|
|
42
63
|
function pureCoreTest(item) {
|
|
64
|
+
const itemCamel = camel(item);
|
|
43
65
|
const typeName = pascal(item);
|
|
44
66
|
const label = title(item);
|
|
45
|
-
return `import {
|
|
67
|
+
return `import { mintEntityId } from "@dads-framework/core/contract";
|
|
68
|
+
import { describe, expect, it } from "vitest";
|
|
46
69
|
|
|
70
|
+
import { ${itemCamel}IdSchema } from "../contract/index.js";
|
|
47
71
|
import { normalize${typeName} } from "./${item}.js";
|
|
48
72
|
|
|
49
73
|
describe("normalize${typeName}", () => {
|
|
50
74
|
it("trims and collapses whitespace in the title", () => {
|
|
51
|
-
|
|
75
|
+
const id = mintEntityId(${itemCamel}IdSchema);
|
|
76
|
+
expect(normalize${typeName}({ id, title: " Sample ${label} " })).toEqual({
|
|
77
|
+
id,
|
|
52
78
|
title: "Sample ${label}",
|
|
53
79
|
});
|
|
54
80
|
});
|
|
55
81
|
|
|
56
82
|
it("rejects an empty title", () => {
|
|
57
|
-
|
|
83
|
+
const id = mintEntityId(${itemCamel}IdSchema);
|
|
84
|
+
expect(() => normalize${typeName}({ id, title: " " })).toThrow("${label} title cannot be empty.");
|
|
58
85
|
});
|
|
59
86
|
});
|
|
60
87
|
`;
|
|
61
88
|
}
|
|
62
|
-
function accessRegistry() {
|
|
63
|
-
|
|
89
|
+
function accessRegistry(item) {
|
|
90
|
+
const itemCamel = camel(item);
|
|
91
|
+
const wireName = item.replaceAll("-", "_");
|
|
92
|
+
return `import { resource, type DslNode } from "@dads-framework/access";
|
|
93
|
+
|
|
94
|
+
import { account } from "../../../libraries/app-runtime/index.js";
|
|
95
|
+
import { ${itemCamel}IdSchema } from "../contract/index.js";
|
|
64
96
|
|
|
65
97
|
// dad:add imports
|
|
66
98
|
|
|
99
|
+
export const ${itemCamel}Resource = resource("${wireName}", {
|
|
100
|
+
id: ${itemCamel}IdSchema,
|
|
101
|
+
roles: { editor: account },
|
|
102
|
+
can: ({ editor }) => ({
|
|
103
|
+
view: editor,
|
|
104
|
+
edit: editor,
|
|
105
|
+
}),
|
|
106
|
+
});
|
|
107
|
+
|
|
67
108
|
export const accessDefinitions: DslNode[] = [
|
|
109
|
+
${itemCamel}Resource,
|
|
68
110
|
// dad:add access
|
|
69
111
|
];
|
|
70
112
|
`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"domain-generator.js","sourceRoot":"","sources":["../../src/resource-generators/domain-generator.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAE5D,MAAM,OAAO,GAAG,oBAAoB,CAAC;AACrC,MAAM,OAAO,GAAG,oBAAoB,CAAC;AAErC,MAAM,UAAU,YAAY,CAAC,IAAoB,EAAE,MAAc;IAC/D,MAAM,SAAS,GAAG,WAAW,MAAM,EAAE,CAAC;IACtC,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,SAAS,WAAW,CAAC,KAAK,SAAS,EAAE,CAAC;QACrD,aAAa,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QAC5B,OAAO;IACT,CAAC;IACD,MAAM,IAAI,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC;IAC9B,IAAI,CAAC,MAAM,CACT,GAAG,SAAS,WAAW,EACvB,YAAY,KAAK,CAAC,MAAM,CAAC,2DAA2D,CACrF,CAAC;IACF,IAAI,CAAC,MAAM,CACT,GAAG,SAAS,YAAY,EACxB,KAAK,MAAM,6JAA6J,CACzK,CAAC;IACF,IAAI,CAAC,MAAM,CAAC,GAAG,SAAS,SAAS,IAAI,KAAK,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC;IAC5D,IAAI,CAAC,MAAM,CAAC,GAAG,SAAS,SAAS,IAAI,UAAU,EAAE,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC;IACrE,IAAI,CAAC,MAAM,CAAC,GAAG,SAAS,oBAAoB,EAAE,cAAc,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"domain-generator.js","sourceRoot":"","sources":["../../src/resource-generators/domain-generator.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAE5D,MAAM,OAAO,GAAG,oBAAoB,CAAC;AACrC,MAAM,OAAO,GAAG,oBAAoB,CAAC;AAErC,MAAM,UAAU,YAAY,CAAC,IAAoB,EAAE,MAAc;IAC/D,MAAM,SAAS,GAAG,WAAW,MAAM,EAAE,CAAC;IACtC,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,SAAS,WAAW,CAAC,KAAK,SAAS,EAAE,CAAC;QACrD,aAAa,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QAC5B,OAAO;IACT,CAAC;IACD,MAAM,IAAI,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC;IAC9B,IAAI,CAAC,MAAM,CACT,GAAG,SAAS,WAAW,EACvB,YAAY,KAAK,CAAC,MAAM,CAAC,2DAA2D,CACrF,CAAC;IACF,IAAI,CAAC,MAAM,CACT,GAAG,SAAS,YAAY,EACxB,KAAK,MAAM,6JAA6J,CACzK,CAAC;IACF,IAAI,CAAC,MAAM,CAAC,GAAG,SAAS,SAAS,IAAI,KAAK,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC;IAC5D,IAAI,CAAC,MAAM,CAAC,GAAG,SAAS,SAAS,IAAI,UAAU,EAAE,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC;IACrE,IAAI,CAAC,MAAM,CAAC,GAAG,SAAS,oBAAoB,EAAE,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC;IACpE,IAAI,CAAC,MAAM,CAAC,GAAG,SAAS,sBAAsB,EAAE,cAAc,CAAC,CAAC;IAChE,IAAI,CAAC,MAAM,CAAC,GAAG,SAAS,kBAAkB,EAAE,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC;IAClE,IAAI,CAAC,MAAM,CACT,GAAG,SAAS,kBAAkB,EAC9B,uLAAuL,CACxL,CAAC;IACF,IAAI,CAAC,MAAM,CAAC,GAAG,SAAS,mBAAmB,EAAE,aAAa,EAAE,CAAC,CAAC;IAC9D,IAAI,CAAC,MAAM,CAAC,GAAG,SAAS,mBAAmB,EAAE,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC;AACrE,CAAC;AAED,SAAS,cAAc,CAAC,IAAY;IAClC,MAAM,SAAS,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC;IAC9B,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;IAC9B,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC;IAC1B,OAAO;;;eAGM,SAAS,8BAA8B,QAAQ,SAAS,KAAK;cAC9D,QAAQ,uBAAuB,SAAS;;eAEvC,SAAS;QAChB,SAAS;;;cAGH,QAAQ,yBAAyB,SAAS;CACvD,CAAC;AACF,CAAC;AAED,SAAS,QAAQ,CAAC,IAAY;IAC5B,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;IAC9B,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC;IAC1B,OAAO,iBAAiB,QAAQ;;cAEpB,QAAQ;iBACL,QAAQ;;;;wBAID,QAAQ;iBACf,QAAQ;;;;2BAIE,QAAQ,WAAW,QAAQ,qBAAqB,QAAQ;;;uBAG5D,KAAK;;;;CAI3B,CAAC;AACF,CAAC;AAED,SAAS,YAAY,CAAC,IAAY;IAChC,MAAM,SAAS,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC;IAC9B,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;IAC9B,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC;IAC1B,OAAO;;;WAGE,SAAS;oBACA,QAAQ,cAAc,IAAI;;qBAEzB,QAAQ;;8BAEC,SAAS;sBACjB,QAAQ,6BAA6B,KAAK;;uBAEzC,KAAK;;;;;8BAKE,SAAS;4BACX,QAAQ,oCAAoC,KAAK;;;CAG5E,CAAC;AACF,CAAC;AAED,SAAS,cAAc,CAAC,IAAY;IAClC,MAAM,SAAS,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC;IAC9B,MAAM,QAAQ,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;IAC3C,OAAO;;;WAGE,SAAS;;;;eAIL,SAAS,wBAAwB,QAAQ;QAChD,SAAS;;;;;;;;;IASb,SAAS;;;CAGZ,CAAC;AACF,CAAC;AAED,SAAS,aAAa;IACpB,OAAO;;;;;;;;;;;;;;CAcR,CAAC;AACF,CAAC;AAED,SAAS,YAAY,CAAC,MAAc;IAClC,OAAO;;;;;;;eAOM,KAAK,CAAC,MAAM,CAAC;WACjB,MAAM;;;;;;;CAOhB,CAAC;AACF,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,IAAoB,EAAE,MAAc;IAChE,IAAI,IAAI,CAAC,IAAI,CAAC,WAAW,MAAM,mBAAmB,CAAC,KAAK,SAAS,EAAE,CAAC;QAClE,MAAM,IAAI,KAAK,CAAC,WAAW,MAAM,8CAA8C,MAAM,SAAS,CAAC,CAAC;IAClG,CAAC;AACH,CAAC;AAED,MAAM,UAAU,WAAW,CAAC,IAAoB,EAAE,GAAW,EAAE,MAAc;IAC3E,MAAM,IAAI,GAAG,QAAQ,GAAG,SAAS,CAAC;IAClC,MAAM,MAAM,GAAG,GAAG,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC;IACxC,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,OAAO,EAAE,YAAY,MAAM,0BAA0B,MAAM,aAAa,CAAC,CAAC;IAChG,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,OAAO,EAAE,KAAK,MAAM,GAAG,CAAC,CAAC;AACjD,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"kit-starter.generated.d.ts","sourceRoot":"","sources":["../../src/starter-project/kit-starter.generated.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,eAAe;;;
|
|
1
|
+
{"version":3,"file":"kit-starter.generated.d.ts","sourceRoot":"","sources":["../../src/starter-project/kit-starter.generated.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,eAAe;;;GAiI3B,CAAC"}
|
|
@@ -17,8 +17,8 @@ export const kitStarterFiles = [
|
|
|
17
17
|
{ path: "apps/web/enterprise-sign-in-form.tsx", content: "import { Button } from \"@dads-framework/ui/elements\";\nimport { Input, Label } from \"@dads-framework/ui/forms\";\nimport { useEffect, useState } from \"react\";\nimport { field, useAction } from \"./actions.js\";\nimport { useWorkbenchCopy } from \"./copy/workbench-copy.js\";\nimport { beginEnterpriseSignIn, readSignInOptions, returnedWithEnterpriseError } from \"./enterprise-sign-in-client.js\";\n\nexport function EnterpriseSignInForm() {\n const t = useWorkbenchCopy();\n const [available, setAvailable] = useState(false);\n const [returnedError, setReturnedError] = useState(() => returnedWithEnterpriseError(new URL(window.location.href)));\n const [open, setOpen] = useState(returnedError);\n const action = useAction();\n\n useEffect(() => {\n const controller = new AbortController();\n void readSignInOptions(controller.signal).then(\n ({ enterpriseSso }) => {\n if (!controller.signal.aborted) setAvailable(enterpriseSso);\n },\n () => {\n if (!controller.signal.aborted) setAvailable(false);\n },\n );\n return () => {\n controller.abort();\n };\n }, []);\n\n if (!available) return null;\n\n return (\n <details\n className=\"enterprise-sign-in\"\n open={open}\n onToggle={(event) => {\n setOpen(event.currentTarget.open);\n }}\n >\n <summary>{t(\"workbench.auth.enterprise.title\")}</summary>\n <form\n className=\"fields\"\n onSubmit={(event) => {\n action.submit(event, async (form) => {\n setReturnedError(false);\n const provider = field(form, \"provider\").trim();\n const destination = await beginEnterpriseSignIn(provider, new URL(window.location.href));\n window.location.assign(destination);\n });\n }}\n >\n <div className=\"field\">\n <Label htmlFor=\"enterprise-provider\">{t(\"workbench.auth.enterprise.provider\")}</Label>\n <Input\n id=\"enterprise-provider\"\n name=\"provider\"\n autoCapitalize=\"none\"\n spellCheck={false}\n maxLength={80}\n required\n aria-describedby=\"enterprise-provider-help\"\n />\n <p id=\"enterprise-provider-help\" className=\"field-hint\">\n {t(\"workbench.auth.enterprise.help\")}\n </p>\n </div>\n {(action.error || returnedError) && (\n <p className=\"error\" role=\"alert\">\n {t(\"workbench.auth.enterprise.error\")}\n </p>\n )}\n <Button variant=\"outline\" disabled={action.pending}>\n {t(action.pending ? \"workbench.auth.enterprise.redirecting\" : \"workbench.auth.enterprise.continue\")}\n </Button>\n </form>\n </details>\n );\n}\n" },
|
|
18
18
|
{ path: "apps/web/examples.css", content: "@import \"@dads-framework/ui/styles/fonts.css\";\n\n:root {\n color-scheme: dark;\n --canvas: #10141d;\n --panel: #181e2a;\n --code: #0e131d;\n --line: #303b50;\n --text: #f2f5fc;\n --muted: #b6c2d6;\n --link: #a9c6ff;\n --mono: \"IBM Plex Mono\", monospace;\n font-family: \"IBM Plex Sans\", system-ui, sans-serif;\n color: var(--text);\n background: var(--canvas);\n}\n\n* {\n box-sizing: border-box;\n}\nbody {\n margin: 0;\n}\na {\n color: var(--link);\n text-underline-offset: 0.2em;\n}\na:hover {\n color: var(--text);\n}\n:focus-visible {\n outline: 2px solid var(--link);\n outline-offset: 4px;\n}\n\n.examples-frame {\n width: min(72rem, calc(100% - 2.5rem));\n margin-inline: auto;\n}\n\n.examples-header {\n background: var(--code);\n border-block-end: 1px solid var(--line);\n}\n\n.examples-header .examples-frame {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n justify-content: space-between;\n gap: 0.75rem 1rem;\n padding-block: 1rem;\n}\n\n.examples-brand {\n color: var(--text);\n font-weight: 650;\n text-decoration: none;\n}\n.back-link,\n.examples-top {\n font-size: 0.875rem;\n}\n\n.examples-intro {\n padding-block: clamp(2.25rem, 6vw, 4.75rem) clamp(1.5rem, 4vw, 2.75rem);\n}\n\n.examples-intro h1 {\n margin: 0 0 0.75rem;\n font-size: clamp(2.2rem, 6vw, 4.5rem);\n line-height: 1.03;\n letter-spacing: -0.04em;\n}\n\n.examples-intro p {\n color: var(--muted);\n margin: 0;\n font-size: 1.1rem;\n}\n\n.examples-layout {\n display: grid;\n grid-template-columns: minmax(12rem, 15rem) minmax(0, 1fr);\n gap: clamp(1.25rem, 4vw, 3rem);\n padding-block-end: 4rem;\n}\n\n.examples-sidebar {\n align-self: start;\n position: sticky;\n top: 1.25rem;\n}\n.examples-sidebar ul {\n list-style: none;\n padding: 0;\n margin: 0 0 0.9rem;\n}\n.examples-sidebar li {\n border-block-end: 1px solid var(--line);\n}\n.examples-sidebar li a {\n display: block;\n padding: 0.78rem 0.5rem;\n color: var(--muted);\n text-decoration: none;\n}\n.examples-sidebar li a:hover {\n color: var(--text);\n background: var(--panel);\n}\n.examples-top {\n margin-inline-start: 0.5rem;\n}\n\n.examples-articles {\n display: grid;\n gap: 1.75rem;\n min-width: 0;\n}\n.example-guide {\n background: var(--panel);\n border: 1px solid var(--line);\n border-radius: 0.85rem;\n min-width: 0;\n padding: clamp(1.15rem, 4vw, 2.6rem);\n scroll-margin-top: 1.25rem;\n line-height: 1.65;\n overflow-wrap: anywhere;\n}\n.example-guide:target {\n border-color: var(--link);\n}\n.example-guide h2 {\n margin: 0 0 1rem;\n font-size: clamp(1.5rem, 4vw, 2.35rem);\n line-height: 1.15;\n letter-spacing: -0.025em;\n}\n.example-guide h3 {\n margin-block: 2rem 0.6rem;\n line-height: 1.25;\n font-size: 1.25rem;\n}\n.example-guide > :last-child {\n margin-block-end: 0;\n}\n.example-guide li + li {\n margin-block-start: 0.35rem;\n}\n.example-guide table {\n width: 100%;\n border-collapse: collapse;\n font-size: 0.95rem;\n}\n.example-guide th,\n.example-guide td {\n border-block-end: 1px solid var(--line);\n padding: 0.65rem 0.75rem;\n text-align: start;\n vertical-align: top;\n}\n.example-guide th {\n background: var(--code);\n}\n.example-guide td {\n color: var(--muted);\n}\n.example-guide pre {\n overflow: auto;\n padding: 1rem;\n border-radius: 0.5rem;\n border: 1px solid var(--line);\n background: var(--code);\n font-size: 0.875rem;\n tab-size: 2;\n}\n.example-guide code {\n font-family: var(--mono);\n}\n.example-guide :not(pre) > code {\n padding: 0.12em 0.3em;\n border-radius: 0.25rem;\n color: var(--link);\n background: var(--code);\n font-size: 0.9em;\n}\n\n@media (max-width: 46rem) {\n .examples-layout {\n grid-template-columns: minmax(0, 1fr);\n }\n .examples-sidebar {\n position: static;\n }\n .examples-top {\n display: none;\n }\n .example-guide th,\n .example-guide td {\n padding-inline: 0.5rem;\n }\n}\n" },
|
|
19
19
|
{ path: "apps/web/main.tsx", content: "import { useWorkbenchCopy, type WorkbenchCopyKey } from \"./copy/workbench-copy.js\";\nimport { onUnauthorizedResponse } from \"@dads-framework/client\";\nimport { Button } from \"@dads-framework/ui/elements\";\nimport { StrictMode, useEffect, useState } from \"react\";\nimport { createRoot } from \"react-dom/client\";\nimport { AccountForm } from \"./account-form.js\";\nimport { describeFailure, useAction } from \"./actions.js\";\nimport { readAccount, signOut, type Account } from \"./auth-client.js\";\nimport { Workbench } from \"./workbench.js\";\nimport \"./styles.css\";\n\nfunction invitationToken() {\n if (window.location.pathname !== \"/accept-tenant-invitation\") return null;\n return new URLSearchParams(window.location.hash.slice(1)).get(\"token\");\n}\n\nfunction App() {\n const t = useWorkbenchCopy();\n const [account, setAccount] = useState<Account | null>();\n const [invitation, setInvitation] = useState(invitationToken);\n const [failure, setFailure] = useState<WorkbenchCopyKey>();\n const [attempt, setAttempt] = useState(0);\n const signOutAction = useAction();\n\n useEffect(() => {\n const controller = new AbortController();\n void readAccount(controller.signal).then(\n (value) => {\n if (!controller.signal.aborted) setAccount(value);\n },\n (fault: unknown) => {\n if (!controller.signal.aborted) setFailure(describeFailure(fault));\n },\n );\n return () => {\n controller.abort();\n };\n }, [attempt]);\n\n useEffect(\n () =>\n onUnauthorizedResponse(() => {\n setAccount(null);\n }),\n [],\n );\n\n return (\n <>\n <header className=\"masthead\">\n <div className=\"masthead-inner\">\n <a href=\"/\" className=\"brand\">\n {t(\"workbench.brand\")}\n </a>\n <nav className=\"masthead-links\" aria-label={t(\"workbench.links\")}>\n <a href=\"/examples.html\">{t(\"workbench.examples\")}</a>\n <a href=\"/api/health\">{t(\"workbench.apiHealth\")}</a>\n {account && (\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={signOutAction.pending}\n onClick={() =>\n void signOutAction.run(async () => {\n await signOut();\n setAccount(null);\n })\n }\n >\n {t(\"workbench.auth.signOut\")}\n </Button>\n )}\n </nav>\n </div>\n </header>\n <main className=\"shell\">\n <div className=\"hero\">\n <p className=\"eyebrow\">{account ? account.email : t(\"workbench.starter\")}</p>\n <h1>{account ? t(\"workbench.title.signedIn\") : t(\"workbench.title.signedOut\")}</h1>\n <p>{t(\"workbench.summary\")}</p>\n </div>\n {signOutAction.error && (\n <p className=\"error\" role=\"alert\">\n {t(signOutAction.error)}\n </p>\n )}\n {failure && (\n <p className=\"error\" role=\"alert\">\n {t(failure)}{\" \"}\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={() => {\n setFailure(undefined);\n setAttempt(attempt + 1);\n }}\n >\n {t(\"workbench.retry\")}\n </Button>\n </p>\n )}\n {account === undefined && failure === undefined && <p role=\"status\">{t(\"workbench.session.loading\")}</p>}\n {account === null && <AccountForm onSignIn={setAccount} hasInvitation={invitation !== null} />}\n {account && (\n <Workbench\n key={account.id}\n invitation={invitation}\n onJoined={() => {\n window.history.replaceState(null, \"\", \"/\");\n setInvitation(null);\n }}\n />\n )}\n </main>\n </>\n );\n}\n\nconst mount = document.getElementById(\"root\");\nif (mount === null) throw new Error(\"The browser entrypoint is missing its root element.\");\ncreateRoot(mount).render(\n <StrictMode>\n <App />\n </StrictMode>,\n);\n" },
|
|
20
|
-
{ path: "apps/web/note-attachments-client.ts", content: "import { getFromApi, sendToApi } from \"@dads-framework/client\";\nimport { defineRoute } from \"@dads-framework/core/contract\";\nimport { z } from \"zod\";\n\nconst attachmentUploadBody = z.strictObject({\n text: z.string().min(1).max(16_384),\n});\n\nconst attachmentUploaded = z.strictObject({\n fileId: z.uuid(),\n});\n\nconst attachmentInspection = z.strictObject({\n bytes: z.number().int(),\n sha256: z.string().length(64),\n});\n\nconst attachmentRecord = z.strictObject({\n text: z.string(),\n inspection: attachmentInspection.nullable(),\n});\n\nexport type NoteAttachmentInspection = z.output<typeof attachmentInspection>;\nexport type NoteAttachmentRecord = z.output<typeof attachmentRecord>;\n\nfunction attachmentCollectionPath(tenantId: string, noteId:
|
|
21
|
-
{ path: "apps/web/note-attachments.tsx", content: "import { StatusBadge } from \"@dads-framework/ui/display\";\nimport { Badge, Button } from \"@dads-framework/ui/elements\";\nimport { Label, Textarea } from \"@dads-framework/ui/forms\";\nimport { Paperclip, RefreshCw } from \"@dads-framework/ui/icons\";\nimport { useState, type SubmitEvent } from \"react\";\nimport { field, useAction } from \"./actions.js\";\nimport { useWorkbenchCopy } from \"./copy/workbench-copy.js\";\nimport { readNoteAttachment, uploadNoteAttachment, type NoteAttachmentRecord } from \"./note-attachments-client.js\";\n\ntype AttachmentItem = {\n readonly fileId: string;\n readonly record: NoteAttachmentRecord | undefined;\n readonly expanded: boolean;\n};\n\ntype NoteAttachmentsProps = {\n readonly tenantId: string;\n readonly noteId:
|
|
20
|
+
{ path: "apps/web/note-attachments-client.ts", content: "import { getFromApi, sendToApi } from \"@dads-framework/client\";\nimport { defineRoute } from \"@dads-framework/core/contract\";\nimport { z } from \"zod\";\nimport type { NoteId } from \"../../domains/notes/web-client/index.js\";\n\nconst attachmentUploadBody = z.strictObject({\n text: z.string().min(1).max(16_384),\n});\n\nconst attachmentUploaded = z.strictObject({\n fileId: z.uuid(),\n});\n\nconst attachmentInspection = z.strictObject({\n bytes: z.number().int(),\n sha256: z.string().length(64),\n});\n\nconst attachmentRecord = z.strictObject({\n text: z.string(),\n inspection: attachmentInspection.nullable(),\n});\n\nexport type NoteAttachmentInspection = z.output<typeof attachmentInspection>;\nexport type NoteAttachmentRecord = z.output<typeof attachmentRecord>;\n\nfunction attachmentCollectionPath(tenantId: string, noteId: NoteId): string {\n return `/tenants/${encodeURIComponent(tenantId)}/notes/${encodeURIComponent(noteId)}/attachments`;\n}\n\nconst uploadRoute = defineRoute(\"POST\", \"/tenants/:tenantId/notes/:noteId/attachments\", attachmentCollectionPath);\n\nconst readRoute = defineRoute(\n \"GET\",\n \"/tenants/:tenantId/notes/:noteId/attachments/:fileId\",\n (tenantId: string, noteId: NoteId, fileId: string) =>\n `${attachmentCollectionPath(tenantId, noteId)}/${encodeURIComponent(fileId)}`,\n);\n\nexport function uploadNoteAttachment(tenantId: string, noteId: NoteId, text: string) {\n return sendToApi({\n route: uploadRoute.bind(tenantId, noteId),\n body: { schema: attachmentUploadBody, value: { text } },\n returns: attachmentUploaded,\n });\n}\n\nexport function readNoteAttachment(tenantId: string, noteId: NoteId, fileId: string, signal?: AbortSignal) {\n return getFromApi({\n route: readRoute.bind(tenantId, noteId, fileId),\n returns: attachmentRecord,\n ...(signal === undefined ? {} : { signal }),\n });\n}\n" },
|
|
21
|
+
{ path: "apps/web/note-attachments.tsx", content: "import { StatusBadge } from \"@dads-framework/ui/display\";\nimport { Badge, Button } from \"@dads-framework/ui/elements\";\nimport { Label, Textarea } from \"@dads-framework/ui/forms\";\nimport { Paperclip, RefreshCw } from \"@dads-framework/ui/icons\";\nimport { useState, type SubmitEvent } from \"react\";\nimport type { NoteId } from \"../../domains/notes/web-client/index.js\";\nimport { field, useAction } from \"./actions.js\";\nimport { useWorkbenchCopy } from \"./copy/workbench-copy.js\";\nimport { readNoteAttachment, uploadNoteAttachment, type NoteAttachmentRecord } from \"./note-attachments-client.js\";\n\ntype AttachmentItem = {\n readonly fileId: string;\n readonly record: NoteAttachmentRecord | undefined;\n readonly expanded: boolean;\n};\n\ntype NoteAttachmentsProps = {\n readonly tenantId: string;\n readonly noteId: NoteId;\n};\n\nexport function NoteAttachments({ tenantId, noteId }: NoteAttachmentsProps) {\n const t = useWorkbenchCopy();\n const upload = useAction();\n const [items, setItems] = useState<readonly AttachmentItem[]>([]);\n const inputId = `attachment-text-${noteId}`;\n\n function prependAttachment(fileId: string, record: NoteAttachmentRecord) {\n setItems((current) => [{ fileId, record, expanded: true }, ...current]);\n }\n\n function updateAttachment(fileId: string, updater: (item: AttachmentItem) => AttachmentItem) {\n setItems((current) => current.map((item) => (item.fileId === fileId ? updater(item) : item)));\n }\n\n function handleSubmit(event: SubmitEvent<HTMLFormElement>) {\n const element = event.currentTarget;\n upload.submit(event, async (form) => {\n const created = await uploadNoteAttachment(tenantId, noteId, field(form, \"attachment\"));\n const record = await readNoteAttachment(tenantId, noteId, created.fileId);\n element.reset();\n prependAttachment(created.fileId, record);\n });\n }\n\n return (\n <details className=\"note-attachments\">\n <summary className=\"note-attachments-summary\">\n <span className=\"note-attachments-title\">\n <Paperclip className=\"size-3.5\" aria-hidden=\"true\" />\n {t(\"workbench.notes.attachments.title\")}\n </span>\n {items.length > 0 && (\n <Badge variant=\"secondary\">{t(\"workbench.notes.attachments.count\", { count: items.length })}</Badge>\n )}\n </summary>\n <div className=\"note-attachments-body\">\n <form className=\"fields\" onSubmit={handleSubmit}>\n <div className=\"field\">\n <Label htmlFor={inputId}>{t(\"workbench.notes.attachments.label\")}</Label>\n <Textarea\n id={inputId}\n name=\"attachment\"\n rows={2}\n required\n maxLength={16384}\n placeholder={t(\"workbench.notes.attachments.placeholder\")}\n />\n </div>\n {upload.error && (\n <p className=\"error\" role=\"alert\">\n {t(upload.error)}\n </p>\n )}\n <Button variant=\"outline\" size=\"sm\" disabled={upload.pending}>\n {t(\"workbench.notes.attachments.upload\")}\n </Button>\n </form>\n {items.length === 0 ? (\n <p className=\"field-hint\">{t(\"workbench.notes.attachments.empty\")}</p>\n ) : (\n <ul className=\"attachment-list\">\n {items.map((item) => (\n <AttachmentRow\n key={item.fileId}\n tenantId={tenantId}\n noteId={noteId}\n item={item}\n onUpdate={(updater) => {\n updateAttachment(item.fileId, updater);\n }}\n />\n ))}\n </ul>\n )}\n </div>\n </details>\n );\n}\n\ntype AttachmentRowProps = {\n readonly tenantId: string;\n readonly noteId: NoteId;\n readonly item: AttachmentItem;\n readonly onUpdate: (updater: (item: AttachmentItem) => AttachmentItem) => void;\n};\n\nfunction AttachmentRow({ tenantId, noteId, item, onUpdate }: AttachmentRowProps) {\n const t = useWorkbenchCopy();\n const inspectAction = useAction();\n\n function applyRecord(record: NoteAttachmentRecord) {\n onUpdate((current) => ({ ...current, record, expanded: true }));\n }\n\n function refreshAttachment() {\n void inspectAction.run(async () => {\n const record = await readNoteAttachment(tenantId, noteId, item.fileId);\n applyRecord(record);\n });\n }\n\n function toggleExpanded() {\n onUpdate((current) => ({ ...current, expanded: !current.expanded }));\n }\n\n const inspection = item.record?.inspection ?? null;\n const shortId = item.fileId.slice(0, 8);\n\n return (\n <li className=\"attachment-item\">\n <div className=\"attachment-row-header\">\n <code className=\"note-id-chip\">{t(\"workbench.notes.attachments.fileLabel\", { shortId })}</code>\n <div className=\"attachment-row-actions\">\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"xs\"\n disabled={inspectAction.pending}\n onClick={refreshAttachment}\n >\n <RefreshCw className=\"size-3\" aria-hidden=\"true\" />\n {t(\"workbench.notes.attachments.refresh\")}\n </Button>\n <Button type=\"button\" variant=\"secondary\" size=\"xs\" onClick={toggleExpanded}>\n {t(item.expanded ? \"workbench.notes.attachments.hide\" : \"workbench.notes.attachments.inspect\")}\n </Button>\n </div>\n </div>\n <div className=\"attachment-status\">\n {inspection ? (\n <StatusBadge tone=\"positive\">\n {t(\"workbench.notes.attachments.digestReady\", {\n bytes: inspection.bytes,\n digest: inspection.sha256.slice(0, 12),\n })}\n </StatusBadge>\n ) : (\n <StatusBadge tone=\"information\">{t(\"workbench.notes.attachments.pendingDigest\")}</StatusBadge>\n )}\n </div>\n {inspectAction.error && (\n <p className=\"error\" role=\"alert\">\n {t(inspectAction.error)}\n </p>\n )}\n {item.expanded && item.record && <pre className=\"attachment-preview\">{item.record.text}</pre>}\n </li>\n );\n}\n" },
|
|
22
22
|
{ path: "apps/web/note-forms.tsx", content: "import { Button, Card, CardContent } from \"@dads-framework/ui/elements\";\nimport { Input, Label, Textarea } from \"@dads-framework/ui/forms\";\nimport { useState } from \"react\";\nimport { createNote } from \"../../domains/notes/web-client/index.js\";\nimport { inviteToTenant, type Tenant } from \"../../domains/tenants/web-client/index.js\";\nimport { field, useAction } from \"./actions.js\";\nimport { useWorkbenchCopy } from \"./copy/workbench-copy.js\";\n\nexport function NewNote({ tenantId, onSaved }: { readonly tenantId: Tenant[\"id\"]; readonly onSaved: () => void }) {\n const t = useWorkbenchCopy();\n const action = useAction();\n const [saved, setSaved] = useState(false);\n return (\n <Card>\n <CardContent>\n <form\n className=\"fields\"\n onSubmit={(event) => {\n const element = event.currentTarget;\n action.submit(event, async (form) => {\n setSaved(false);\n await createNote(tenantId, field(form, \"text\"));\n element.reset();\n setSaved(true);\n onSaved();\n });\n }}\n >\n <div className=\"field\">\n <Label htmlFor=\"note-text\">{t(\"workbench.notes.new\")}</Label>\n <Textarea\n id=\"note-text\"\n name=\"text\"\n rows={3}\n required\n maxLength={2000}\n placeholder={t(\"workbench.notes.placeholder\")}\n />\n </div>\n {action.error && (\n <p className=\"error\" role=\"alert\">\n {t(action.error)}\n </p>\n )}\n {saved && <p role=\"status\">{t(\"workbench.notes.saved\")}</p>}\n <Button disabled={action.pending}>{t(\"workbench.notes.add\")}</Button>\n </form>\n </CardContent>\n </Card>\n );\n}\n\nexport function InviteCollaborator({ tenantId }: { readonly tenantId: Tenant[\"id\"] }) {\n const t = useWorkbenchCopy();\n const action = useAction();\n const [invited, setInvited] = useState(false);\n return (\n <details className=\"invite\">\n <summary>{t(\"workbench.invite.open\")}</summary>\n <form\n className=\"fields\"\n onSubmit={(event) => {\n const element = event.currentTarget;\n action.submit(event, async (form) => {\n setInvited(false);\n await inviteToTenant(tenantId, field(form, \"email\"));\n element.reset();\n setInvited(true);\n });\n }}\n >\n <div className=\"field\">\n <Label htmlFor=\"invite-email\">{t(\"workbench.invite.email\")}</Label>\n <Input id=\"invite-email\" name=\"email\" type=\"email\" required />\n </div>\n {action.error && (\n <p className=\"error\" role=\"alert\">\n {t(action.error)}\n </p>\n )}\n {invited && <p role=\"status\">{t(\"workbench.invite.sent\")}</p>}\n <Button variant=\"outline\" disabled={action.pending}>\n {t(\"workbench.invite.send\")}\n </Button>\n </form>\n </details>\n );\n}\n" },
|
|
23
23
|
{ path: "apps/web/note-list.tsx", content: "import type { ApiPage } from \"@dads-framework/client\";\nimport { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from \"@dads-framework/ui/display\";\nimport { Badge, Button, Card, CardContent } from \"@dads-framework/ui/elements\";\nimport { Input, Label } from \"@dads-framework/ui/forms\";\nimport { FileSpreadsheet, FileText, Search, X } from \"@dads-framework/ui/icons\";\nimport { useState } from \"react\";\nimport { exportNote, type Note, type NoteExportFormat } from \"../../domains/notes/web-client/index.js\";\nimport { useAction } from \"./actions.js\";\nimport { useWorkbenchCopy } from \"./copy/workbench-copy.js\";\nimport { NoteAttachments } from \"./note-attachments.js\";\n\ntype NoteListProps = {\n readonly notes: ApiPage<Note>;\n readonly page: number;\n readonly exportEnabled: boolean;\n readonly onChangePage: (page: number) => void;\n};\n\nexport function NoteList({ notes, page, exportEnabled, onChangePage }: NoteListProps) {\n const t = useWorkbenchCopy();\n const [query, setQuery] = useState(\"\");\n const normalized = query.trim().toLocaleLowerCase();\n const filtered = normalized ? notes.items.filter((note) => matchesNote(note, normalized)) : notes.items;\n const totalPages = Math.max(1, Math.ceil(notes.meta.total / notes.meta.perPage));\n const showPagination = notes.meta.page > 1 || notes.meta.total > notes.meta.perPage;\n\n return (\n <div className=\"notes-list\">\n {notes.items.length > 0 && (\n <NoteSearchBar\n query={query}\n shownCount={filtered.length}\n pageCount={notes.items.length}\n onQueryChange={setQuery}\n />\n )}\n {notes.items.length === 0 && (\n <Card className=\"empty-notes-card\">\n <CardContent>\n <Empty>\n <EmptyHeader>\n <EmptyMedia variant=\"icon\">\n <FileText aria-hidden=\"true\" />\n </EmptyMedia>\n <EmptyTitle>{t(\"workbench.notes.emptyTitle\")}</EmptyTitle>\n <EmptyDescription>{t(\"workbench.notes.emptyDescription\")}</EmptyDescription>\n </EmptyHeader>\n </Empty>\n </CardContent>\n </Card>\n )}\n {notes.items.length > 0 && filtered.length === 0 && (\n <Card className=\"empty-notes-card\">\n <CardContent>\n <Empty>\n <EmptyHeader>\n <EmptyMedia variant=\"icon\">\n <Search aria-hidden=\"true\" />\n </EmptyMedia>\n <EmptyTitle>{t(\"workbench.notes.noMatchTitle\")}</EmptyTitle>\n <EmptyDescription>{t(\"workbench.notes.noMatchDescription\")}</EmptyDescription>\n </EmptyHeader>\n <EmptyContent>\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n onClick={() => {\n setQuery(\"\");\n }}\n >\n {t(\"workbench.notes.clearSearch\")}\n </Button>\n </EmptyContent>\n </Empty>\n </CardContent>\n </Card>\n )}\n {filtered.map((note) => (\n <NoteRow key={note.id} note={note} exportEnabled={exportEnabled} />\n ))}\n {showPagination && (\n <nav className=\"pagination\" aria-label={t(\"workbench.notes.pages\")}>\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={page <= 1 || page !== notes.meta.page}\n onClick={() => {\n onChangePage(page - 1);\n }}\n >\n {t(\"workbench.notes.previous\")}\n </Button>\n <span className=\"pagination-label\">\n {t(\"workbench.notes.pageSummary\", {\n number: notes.meta.page,\n pages: totalPages,\n })}\n </span>\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={page !== notes.meta.page || page * notes.meta.perPage >= notes.meta.total}\n onClick={() => {\n onChangePage(page + 1);\n }}\n >\n {t(\"workbench.notes.next\")}\n </Button>\n </nav>\n )}\n </div>\n );\n}\n\ntype NoteSearchBarProps = {\n readonly query: string;\n readonly shownCount: number;\n readonly pageCount: number;\n readonly onQueryChange: (value: string) => void;\n};\n\nfunction NoteSearchBar({ query, shownCount, pageCount, onQueryChange }: NoteSearchBarProps) {\n const t = useWorkbenchCopy();\n return (\n <div className=\"notes-toolbar\">\n <div className=\"notes-search\">\n <Label htmlFor=\"notes-filter\" className=\"sr-only\">\n {t(\"workbench.notes.searchLabel\")}\n </Label>\n <Search className=\"notes-search-icon size-4\" aria-hidden=\"true\" />\n <Input\n id=\"notes-filter\"\n type=\"search\"\n value={query}\n className=\"notes-search-input\"\n placeholder={t(\"workbench.notes.searchPlaceholder\")}\n onChange={(event) => {\n onQueryChange(event.currentTarget.value);\n }}\n />\n {query.length > 0 && (\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"xs\"\n onClick={() => {\n onQueryChange(\"\");\n }}\n >\n <X className=\"size-3\" aria-hidden=\"true\" />\n {t(\"workbench.notes.clearSearch\")}\n </Button>\n )}\n </div>\n <Badge variant=\"outline\">{t(\"workbench.notes.count\", { shown: shownCount, total: pageCount })}</Badge>\n </div>\n );\n}\n\nconst exportFormats: readonly NoteExportFormat[] = [\"csv\", \"pdf\"];\n\nfunction NoteRow({ note, exportEnabled }: { readonly note: Note; readonly exportEnabled: boolean }) {\n const t = useWorkbenchCopy();\n const action = useAction();\n const stats = summarizeNote(note.text);\n const shortId = note.id.slice(0, 8);\n\n function download(format: NoteExportFormat) {\n return action.run(async () => {\n const file = await exportNote(note.tenantId, note.id, format);\n downloadNote(file, format);\n });\n }\n\n return (\n <article className=\"note\">\n <div className=\"note-header\">\n <div className=\"note-meta\">\n <code className=\"note-id-chip\">{t(\"workbench.notes.noteId\", { shortId })}</code>\n <span className=\"note-stats\">\n {t(\"workbench.notes.summary\", {\n words: stats.words,\n chars: stats.chars,\n })}\n </span>\n </div>\n {exportEnabled ? (\n <div className=\"note-actions\">\n {exportFormats.map((format) => (\n <Button\n key={format}\n variant=\"outline\"\n size=\"xs\"\n disabled={action.pending}\n onClick={() => void download(format)}\n >\n {format === \"csv\" ? (\n <FileSpreadsheet className=\"size-3.5\" aria-hidden=\"true\" />\n ) : (\n <FileText className=\"size-3.5\" aria-hidden=\"true\" />\n )}\n {t(format === \"csv\" ? \"workbench.notes.export.csv\" : \"workbench.notes.export.pdf\")}\n </Button>\n ))}\n </div>\n ) : (\n <span className=\"note-export-hint\">{t(\"workbench.notes.export.locked\")}</span>\n )}\n </div>\n <p className=\"note-body\">{note.text}</p>\n {action.error && (\n <p className=\"error\" role=\"alert\">\n {t(action.error)}\n </p>\n )}\n <NoteAttachments tenantId={note.tenantId} noteId={note.id} />\n </article>\n );\n}\n\nfunction matchesNote(note: Note, query: string): boolean {\n return note.text.toLocaleLowerCase().includes(query) || note.id.toLocaleLowerCase().includes(query);\n}\n\nfunction summarizeNote(text: string): {\n readonly words: number;\n readonly chars: number;\n} {\n const trimmed = text.trim();\n const words = trimmed.length === 0 ? 0 : trimmed.split(/\\s+/u).length;\n return { words, chars: text.length };\n}\n\nfunction downloadNote(file: { readonly base64: string; readonly contentType: string }, format: NoteExportFormat) {\n const bytes = Uint8Array.from(atob(file.base64), (character) => character.charCodeAt(0));\n const content = new Blob([bytes], { type: file.contentType });\n const url = URL.createObjectURL(content);\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = `note.${format}`;\n link.click();\n window.setTimeout(() => {\n URL.revokeObjectURL(url);\n }, 1000);\n}\n" },
|
|
24
24
|
{ path: "apps/web/notes.tsx", content: "import { Alert, AlertDescription, StatusBadge } from \"@dads-framework/ui/display\";\nimport { Badge, Button } from \"@dads-framework/ui/elements\";\nimport { useEffect, useState } from \"react\";\nimport { listNotes, notesExport, readFeatures } from \"../../domains/notes/web-client/index.js\";\nimport type { Tenant } from \"../../domains/tenants/web-client/index.js\";\nimport { describeFailure } from \"./actions.js\";\nimport { useWorkbenchCopy, type WorkbenchCopyKey } from \"./copy/workbench-copy.js\";\nimport { InviteCollaborator, NewNote } from \"./note-forms.js\";\nimport { NoteList } from \"./note-list.js\";\n\nexport function Notes({ tenant }: { readonly tenant: Tenant }) {\n const t = useWorkbenchCopy();\n const [page, setPage] = useState(1);\n const [reload, setReload] = useState(0);\n const [notes, setNotes] = useState<Awaited<ReturnType<typeof listNotes>>>();\n const [features, setFeatures] = useState<readonly string[]>();\n const [loadError, setLoadError] = useState<WorkbenchCopyKey>();\n\n useEffect(() => {\n const controller = new AbortController();\n void Promise.all([listNotes(tenant.id, page, controller.signal), readFeatures(tenant.id, controller.signal)]).then(\n ([result, state]) => {\n if (controller.signal.aborted) return;\n setNotes(result);\n setFeatures(state.features);\n },\n (fault: unknown) => {\n if (!controller.signal.aborted) setLoadError(describeFailure(fault));\n },\n );\n return () => {\n controller.abort();\n };\n }, [tenant.id, page, reload]);\n\n function refresh() {\n setLoadError(undefined);\n setReload((previous) => previous + 1);\n }\n\n const exportEnabled = features?.includes(notesExport) === true;\n\n return (\n <section className=\"notes\" aria-labelledby=\"workspace-heading\">\n <div className=\"section-heading\">\n <div className=\"section-heading-group\">\n <h3 id=\"workspace-heading\" className=\"section-subheading\">\n {t(\"workbench.notes.eyebrow\")}\n </h3>\n {notes && (\n <Badge variant=\"secondary\">\n {t(\"workbench.notes.count\", {\n shown: notes.items.length,\n total: notes.meta.total,\n })}\n </Badge>\n )}\n </div>\n {features && (\n <StatusBadge tone={exportEnabled ? \"positive\" : \"neutral\"}>\n {t(exportEnabled ? \"workbench.notes.export.on\" : \"workbench.notes.export.off\")}\n </StatusBadge>\n )}\n </div>\n <NewNote tenantId={tenant.id} onSaved={refresh} />\n {loadError && (\n <Alert variant=\"destructive\">\n <AlertDescription>\n <span>{t(loadError)}</span>\n <Button variant=\"outline\" size=\"xs\" onClick={refresh}>\n {t(\"workbench.retry\")}\n </Button>\n </AlertDescription>\n </Alert>\n )}\n {notes === undefined && loadError === undefined && (\n <p className=\"field-hint\" role=\"status\">\n {t(\"workbench.notes.loading\")}\n </p>\n )}\n {notes && <NoteList notes={notes} page={page} exportEnabled={exportEnabled} onChangePage={setPage} />}\n <InviteCollaborator tenantId={tenant.id} />\n </section>\n );\n}\n" },
|
|
@@ -47,7 +47,7 @@ export const kitStarterFiles = [
|
|
|
47
47
|
{ path: "assembly/main.ts", content: "import { startTelemetry } from \"@dads-framework/http/telemetry\";\nimport { readEnvironment } from \"./config.js\";\nimport { developmentMail } from \"./dev-mail.js\";\nimport { readEnterpriseConfiguration } from \"./enterprise-config.js\";\nimport { readFeaturePreview } from \"./feature-previews.js\";\n\nconst environment = readEnvironment(process.env);\nconst enterprise = readEnterpriseConfiguration(process.env);\nconst featurePreview = readFeaturePreview(process.env);\nconst logMail = environment.DADS_DEV_LOG_MAIL === \"1\";\nif (logMail && (environment.NODE_ENV === \"production\" || environment.HOST !== \"127.0.0.1\")) {\n throw new Error(\"Local mail logging requires a development server on 127.0.0.1.\");\n}\n\nconst telemetry = await startTelemetry({\n serviceName: `dads-${environment.DADS_API}`,\n});\nconst { startApp } = await import(\"./start-app.js\");\ntry {\n const app = await startApp(\n environment.DADS_API,\n {\n databaseUrl: environment.DATABASE_URL,\n baseUrl: environment.baseUrl,\n secret: environment.DADS_IDENTITY_SECRET,\n enterprise,\n ...(featurePreview === undefined ? {} : { featurePreview }),\n preparePermissionChecks: environment.DADS_PREPARE_PERMISSION_CHECKS === \"1\",\n fileStorageDirectory: environment.DADS_FILE_STORAGE_DIR,\n ...(logMail || environment.NODE_ENV === \"production\"\n ? { enqueueEmail: developmentMail(logMail) }\n : { mailSpoolDirectory: environment.DADS_MAIL_SPOOL_DIR }),\n },\n telemetry,\n );\n try {\n await app.listen({ host: environment.HOST, port: environment.PORT });\n } catch (fault) {\n await app.close();\n throw fault;\n }\n const close = (): void => {\n void app\n .close()\n .finally(() => telemetry?.shutdown())\n .catch(() => {\n process.exitCode = 1;\n });\n };\n process.once(\"SIGTERM\", close);\n process.once(\"SIGINT\", close);\n} catch (fault) {\n await telemetry?.shutdown();\n throw fault;\n}\n" },
|
|
48
48
|
{ path: "assembly/migrate.ts", content: "import { z } from \"zod\";\nimport { migrate } from \"./migrations.js\";\n\nawait migrate(z.url().parse(process.env[\"DATABASE_URL\"]));\n" },
|
|
49
49
|
{ path: "assembly/migrations.ts", content: "import { fileURLToPath } from \"node:url\";\nimport { runNodePgMigrations, type MigrationSource } from \"@dads-framework/postgres/migrations\";\n// dad:add imports\n\nconst sources: readonly MigrationSource[] = [\n {\n root: \"migrations\",\n owner: \"starter\",\n files: /^migrations\\/[^/]+\\.migration\\.ts$/,\n required: true,\n },\n // dad:add migrations\n];\n\nexport function migrate(databaseUrl: string) {\n return runNodePgMigrations({\n databaseUrl,\n workspace: {\n root: fileURLToPath(new URL(\"..\", import.meta.url)),\n sources,\n moduleAliases: {\n \"@dads-framework/feature-flags-postgres\": \"migrations/support/feature-flags.ts\",\n },\n },\n });\n}\n" },
|
|
50
|
-
{ path: "assembly/model.ts", content: "import { definePlugin } from \"@dads-framework/core/plugin\";\nimport { accountAccess, tenantAccess } from \"../libraries/app-runtime/index.js\";\n\nexport const starterAccess = definePlugin({\n name: \"starter-access\",\n contributes: { access:
|
|
50
|
+
{ path: "assembly/model.ts", content: "import type { DslNode } from \"@dads-framework/access\";\nimport { definePlugin } from \"@dads-framework/core/plugin\";\nimport { accountAccess, tenantAccess } from \"../libraries/app-runtime/index.js\";\n\nconst starterAccessNodes: readonly DslNode[] = [accountAccess, tenantAccess.tenant];\n\nexport const starterAccess = definePlugin({\n name: \"starter-access\",\n contributes: { access: starterAccessNodes },\n});\n" },
|
|
51
51
|
{ path: "assembly/protected-write.ts", content: "import { conflict, notFound } from \"@dads-framework/core/errors\";\nimport type { DrizzleHandle } from \"@dads-framework/postgres\";\nimport { PostgresSerializationConflict, type PostgresAuthorization } from \"@dads-framework/postgres-access\";\nimport { withProtectedDrizzleTransaction } from \"@dads-framework/postgres-access/drizzle\";\n\nimport type { WriteWithPermission } from \"../libraries/app-runtime/index.js\";\n\nexport function createProtectedWrite(\n database: DrizzleHandle,\n authorization: PostgresAuthorization,\n): WriteWithPermission {\n return async ({ subject, permission, resourceId }, write) => {\n try {\n return await withProtectedDrizzleTransaction(\n { database, authorization },\n async ({ tx, authorization: scoped }) => {\n const allowed = await scoped.check({\n subject,\n permission: permission.permissionName,\n resource: { type: permission.entityWireName, id: resourceId },\n });\n if (!allowed) throw notFound(\"RESOURCE_NOT_FOUND\", \"Resource not found\");\n return write(tx, scoped);\n },\n );\n } catch (fault) {\n if (fault instanceof PostgresSerializationConflict) {\n throw conflict(fault.code, \"The transaction could not finish. Retry the request.\", { retryable: true });\n }\n throw fault;\n }\n };\n}\n" },
|
|
52
52
|
{ path: "assembly/read-local-mail.mjs", content: "import { readdir, readFile, stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport process from \"node:process\";\nimport { z } from \"zod\";\n\nconst envelope = z.object({\n to: z.array(z.object({ address: z.string() })),\n subject: z.string(),\n text: z.string(),\n});\n\nconst spool = process.env[\"DADS_MAIL_SPOOL_DIR\"];\nif (!spool) throw new Error(\"The local mail spool is unavailable.\");\n\nasync function mailEntries(directory) {\n try {\n return await readdir(directory, { withFileTypes: true });\n } catch (fault) {\n if (typeof fault === \"object\" && fault !== null && \"code\" in fault && fault.code === \"ENOENT\") return [];\n throw fault;\n }\n}\n\nasync function readLatestMail(directory) {\n const entries = await mailEntries(directory);\n const files = entries.filter((entry) => entry.isFile() && entry.name.endsWith(\".json\"));\n const ordered = await Promise.all(\n files.map(async ({ name }) => {\n const path = join(directory, name);\n return { path, updated: (await stat(path)).mtimeMs };\n }),\n );\n ordered.sort((left, right) => right.updated - left.updated);\n return Promise.all(\n ordered.slice(0, 20).map(async ({ path }) => envelope.parse(JSON.parse(await readFile(path, \"utf8\")))),\n );\n}\n\nconst mail = await readLatestMail(spool);\nif (process.argv.includes(\"--json\")) {\n process.stdout.write(JSON.stringify({ ok: true, mail }) + \"\\n\");\n} else if (mail.length === 0) {\n process.stdout.write(\"No mail has been delivered yet.\\n\");\n} else {\n process.stdout.write(\n mail\n .map(\n ({ to, subject, text }) => `To: ${to.map(({ address }) => address).join(\", \")}\\nSubject: ${subject}\\n\\n${text}`,\n )\n .join(\"\\n\\n\") + \"\\n\",\n );\n}\n" },
|
|
53
53
|
{ path: "assembly/scim-binding-route.test.ts", content: "import { relationshipWrite } from \"@dads-framework/access/runtime\";\nimport { FakeAuthorization } from \"@dads-framework/access/testing\";\nimport { buildTestApp } from \"@dads-framework/http/testing\";\nimport { TenantUnavailableError } from \"@dads-framework/identity/tenants\";\nimport { expect, it, vi } from \"vitest\";\n\nimport { sessionSubjects } from \"./session-subjects.js\";\nimport { scimBindingRoutes } from \"../domains/tenants/index.js\";\nimport { account, tenantAccess } from \"../libraries/app-runtime/index.js\";\n\nconst origin = \"http://127.0.0.1:3000\";\nconst alpha = \"00000000-0000-4000-8000-000000000001\";\nconst beta = \"00000000-0000-4000-8000-000000000002\";\nconst scimId = \"00000000-0000-4000-8000-000000000003\";\nconst owner = { type: account.wireName, id: \"owner\" };\nconst member = { type: account.wireName, id: \"member\" };\nconst permission = tenantAccess.tenant.permissions.manage_tenant;\n\nit(\"binds an existing member only for an owner of an enabled tenant\", async () => {\n const bindScimUser = vi\n .fn<Parameters<typeof scimBindingRoutes>[0][\"bindScimUser\"]>()\n .mockImplementation((_actor, _tenant, _scimUser, account) =>\n account === member.id ? Promise.resolve() : Promise.reject(new TenantUnavailableError()),\n );\n const auth = new FakeAuthorization({\n [permission.entityWireName]: { [permission.permissionName]: [\"owner\"] },\n });\n for (const tenantId of [alpha, beta]) {\n auth.seed(relationshipWrite({ type: permission.entityWireName, id: tenantId }, \"owner\", owner));\n auth.seed(relationshipWrite({ type: permission.entityWireName, id: tenantId }, \"member\", member));\n }\n\n const readSession = vi.fn((headers: Headers) => {\n const cookie = headers.get(\"cookie\");\n if (cookie === null) return Promise.resolve(null);\n const id = cookie === \"password-owner\" ? owner.id : cookie;\n return Promise.resolve({\n account: { id, email: `${id}@example.test`, emailVerified: true },\n expiresAt: new Date(\"2099-01-01\"),\n });\n });\n const readTenantSession = vi.fn((headers: Headers, tenantId: string) =>\n tenantId === alpha && headers.get(\"cookie\") === \"password-owner\" ? Promise.resolve(null) : readSession(headers),\n );\n const app = await buildTestApp({\n routes: scimBindingRoutes({ bindScimUser }, origin, [alpha]),\n subjects: sessionSubjects(\n { handle: () => Promise.resolve(new Response(null)), readSession },\n { readTenantSession },\n ),\n authorization: auth,\n });\n\n const bind = (tenant: string, cookie?: string, requestOrigin = origin, accountId = member.id) =>\n app.inject({\n method: \"POST\",\n url: `/tenants/${tenant}/scim/users/${scimId}/bind`,\n headers: {\n origin: requestOrigin,\n ...(cookie === undefined ? {} : { cookie }),\n },\n payload: { accountId },\n });\n\n try {\n expect((await bind(alpha)).statusCode).toBe(401);\n expect((await bind(alpha, \"member\")).statusCode).toBe(404);\n expect((await bind(alpha, \"password-owner\")).statusCode).toBe(401);\n expect(readTenantSession).toHaveBeenCalledWith(expect.any(Headers), alpha);\n expect((await bind(beta, \"owner\")).statusCode).toBe(404);\n expect((await bind(alpha, \"owner\", \"https://elsewhere.example.test\")).statusCode).toBe(403);\n expect(bindScimUser).not.toHaveBeenCalled();\n expect((await bind(alpha, \"owner\", origin, \"unavailable\")).statusCode).toBe(404);\n expect((await bind(alpha, \"owner\")).statusCode).toBe(204);\n expect(bindScimUser).toHaveBeenLastCalledWith(owner.id, alpha, scimId, member.id);\n } finally {\n await app.close();\n }\n});\n" },
|
|
@@ -58,21 +58,22 @@ export const kitStarterFiles = [
|
|
|
58
58
|
{ path: "assembly/staff-impersonation-services.ts", content: "import type { Identity } from \"@dads-framework/identity\";\nimport { createImpersonation, type ImpersonationOptions } from \"@dads-framework/identity/impersonation\";\nimport type { EnterpriseBetterAuthIdentity } from \"@dads-framework/identity/better-auth\";\nimport { createPostgresImpersonationStore } from \"@dads-framework/identity/better-auth/impersonation-store\";\nimport type { createPostgresConnection } from \"@dads-framework/postgres\";\nimport type { Tenants } from \"@dads-framework/identity/tenants\";\n\nimport {\n configureStaffImpersonation,\n readTenantAsTarget,\n staffImpersonationConfiguration,\n type StaffImpersonationConfiguration,\n} from \"../domains/support/index.js\";\nimport type { ServiceConfiguration } from \"./services.js\";\n\nexport type StaffImpersonationServices = {\n readonly staffImpersonation: ReturnType<typeof configureStaffImpersonation> | undefined;\n};\n\nexport function openStaffImpersonationServices(\n pool: ReturnType<typeof createPostgresConnection>[\"pool\"],\n config: ServiceConfiguration,\n {\n identity,\n enterpriseIdentity,\n }: {\n readonly identity: Identity;\n readonly enterpriseIdentity: EnterpriseBetterAuthIdentity | undefined;\n },\n tenants: Tenants,\n): StaffImpersonationServices {\n if (config.enterprise?.staffImpersonation === undefined) return { staffImpersonation: undefined };\n const configuration = staffImpersonationConfiguration.parse(config.enterprise.staffImpersonation);\n const { tenantId } = configuration;\n const persistence = createPostgresImpersonationStore(pool);\n const impersonation = createImpersonation({\n ...persistence,\n store: {\n ...persistence.store,\n async read(id) {\n const stored = await persistence.store.read(id);\n return stored?.tenantId === tenantId ? stored : null;\n },\n },\n identity:\n enterpriseIdentity === undefined\n ? identity\n : {\n readSession: (headers) => enterpriseIdentity.readTenantSession(headers, tenantId),\n },\n lifetimeMs: 5 * 60 * 1000,\n authorize: staffSupportPolicy(configuration, tenants),\n });\n return {\n staffImpersonation: configureStaffImpersonation({\n baseUrl: config.baseUrl,\n tenantId,\n impersonation,\n tenants,\n }),\n };\n}\n\nfunction staffSupportPolicy(\n { tenantId, staffAccountIds, revokerAccountIds }: StaffImpersonationConfiguration,\n tenants: Tenants,\n): ImpersonationOptions[\"authorize\"] {\n const staff = new Set(staffAccountIds);\n const revokers = new Set(revokerAccountIds);\n return async (scope) => {\n if (scope.tenantId !== tenantId) return false;\n if (scope.action === \"revoke\") return revokers.has(scope.actorAccountId);\n if (!staff.has(scope.actorAccountId)) return false;\n return (await readTenantAsTarget(tenants, scope.effectiveAccountId, tenantId)) !== null;\n };\n}\n" },
|
|
59
59
|
{ path: "assembly/start-app.ts", content: "import { compileAccess } from \"@dads-framework/access\";\nimport { anonymousActor } from \"@dads-framework/core/audit-actor\";\nimport { startHttpHost, type HttpProtocolMount } from \"@dads-framework/http\";\nimport type { TelemetryRuntime } from \"@dads-framework/http/telemetry\";\nimport { IDENTITY_PATH } from \"@dads-framework/identity/better-auth\";\nimport { sql } from \"drizzle-orm\";\n\nimport { scimBindingRoutes } from \"../domains/tenants/index.js\";\nimport { tenantAccess } from \"../libraries/app-runtime/index.js\";\nimport { apiEntrypoints, type ApiName } from \"./api-entrypoints.js\";\nimport { configureFeaturePreviews } from \"./feature-previews.js\";\nimport { openServices, provideServices, type HostServices, type ServiceConfiguration } from \"./services.js\";\nimport { sessionSubjects } from \"./session-subjects.js\";\nimport { createSignInOptionsRoutes } from \"./sign-in-options-route.js\";\n\nexport async function startApp(name: ApiName, config: ServiceConfiguration, telemetry?: TelemetryRuntime) {\n const provider = provideServices((scope) => openServices(scope, config, model, composed.flags, name === \"staff\"));\n const composed = apiEntrypoints[name](provider);\n const model = compileAccess(composed.access, { allowLookupResourcesOn: [tenantAccess.tenant] });\n const running = await composed.start();\n try {\n const services = running.read(provider);\n const { authorization, identity, enterpriseIdentity, scimHandler, tenants, invitationOrigin, db, flags, local } =\n services;\n const featureState =\n name === \"customer\" && config.featurePreview !== undefined\n ? configureFeaturePreviews({\n configuration: config.featurePreview,\n definitions: composed.flags,\n flags,\n authorization,\n })\n : undefined;\n await local.prepareFiles();\n local.queue.register([...services.mailJobs, ...running.jobs]);\n await local.queue.start();\n const scimRoutes =\n name === \"customer\" && scimHandler !== undefined\n ? scimBindingRoutes(tenants, invitationOrigin, config.enterprise?.scim?.map(({ tenantId }) => tenantId) ?? [])\n : [];\n return await startHttpHost({\n baseUrl: config.baseUrl,\n diagnostics: local.diagnostics,\n requestLog: () => local.requestLog,\n ...(telemetry === undefined ? {} : { telemetry }),\n mounts: buildProtocolMounts(name, services),\n health: {\n pingDatabase: async () => {\n await db.execute(sql`select 1`);\n },\n pingCriticalServices: async () => {\n await Promise.all([local.queue.inspect(), local.checkFiles()]);\n },\n },\n routes: [...running.routes, ...scimRoutes, ...createSignInOptionsRoutes(enterpriseIdentity !== undefined)],\n accessModel: model,\n subjects: sessionSubjects(identity, enterpriseIdentity),\n authorization,\n ...(featureState === undefined ? {} : { featureState }),\n auditActorForSubject: ({ subject, requestId }) =>\n subject === null ? anonymousActor(requestId) : { kind: \"account\", id: subject.id, requestId },\n onClose: () => running.stop(),\n });\n } catch (fault) {\n await running.stop();\n throw fault;\n }\n}\n\nfunction buildProtocolMounts(\n name: ApiName,\n services: Pick<HostServices, \"identity\" | \"scimHandler\" | \"staffImpersonation\">,\n): readonly HttpProtocolMount[] {\n const mounts: HttpProtocolMount[] = [{ prefix: IDENTITY_PATH, handler: services.identity.handle }];\n if (name === \"customer\" && services.scimHandler !== undefined) {\n mounts.push({\n prefix: \"/scim/v2\",\n handler: services.scimHandler,\n options: { methods: [\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"] },\n });\n }\n if (name === \"staff\" && services.staffImpersonation !== undefined) {\n mounts.push({\n prefix: \"/api/staff/impersonation\",\n handler: services.staffImpersonation,\n options: { methods: [\"POST\"], servePrefixRoot: true, bodyLimitBytes: 1024 },\n });\n }\n return mounts;\n}\n" },
|
|
60
60
|
{ path: "dads.project.json", content: "{\n \"schemaVersion\": 1,\n \"packages\": [\n {\n \"name\": \"starter-app\",\n \"root\": \"apps\",\n \"kind\": \"application\",\n \"responsibility\": \"Selects domain routes for each named API.\",\n \"allowedDependencies\": [\n \"@dads-framework/access\",\n \"@dads-framework/audit\",\n \"@dads-framework/client\",\n \"@dads-framework/core\",\n \"@dads-framework/feature-flags\",\n \"@dads-framework/http\",\n \"@dads-framework/identity\",\n \"@dads-framework/postgres\",\n \"@dads-framework/postgres-access\",\n \"@dads-framework/ui\",\n \"drizzle-orm\",\n \"node-pg-migrate\",\n \"react\",\n \"react-dom\",\n \"tsx\",\n \"zod\"\n ],\n \"verification\": [\"npm run verify\"],\n \"skills\": []\n },\n {\n \"name\": \"assembly\",\n \"root\": \"assembly\",\n \"kind\": \"binding\",\n \"responsibility\": \"Builds the runtime and applies registered migrations.\",\n \"allowedDependencies\": [\n \"@dads-framework/access\",\n \"@dads-framework/audit\",\n \"@dads-framework/core\",\n \"@dads-framework/feature-flags\",\n \"@dads-framework/http\",\n \"@dads-framework/identity\",\n \"@dads-framework/postgres\",\n \"@dads-framework/postgres-access\",\n \"drizzle-orm\",\n \"node-pg-migrate\",\n \"tsx\",\n \"zod\"\n ],\n \"verification\": [\"npm run verify\"],\n \"skills\": []\n },\n {\n \"name\": \"domains-notes\",\n \"root\": \"domains/notes\",\n \"kind\": \"core\",\n \"responsibility\": \"Owns the notes contracts and routes.\",\n \"allowedDependencies\": [\n \"@dads-framework/access\",\n \"@dads-framework/audit\",\n \"@dads-framework/client\",\n \"@dads-framework/core\",\n \"@dads-framework/feature-flags\",\n \"@dads-framework/http\",\n \"@dads-framework/identity\",\n \"@dads-framework/postgres\",\n \"@dads-framework/postgres-access\",\n \"@dads-framework/ui\",\n \"drizzle-orm\",\n \"node-pg-migrate\",\n \"tsx\",\n \"zod\"\n ],\n \"verification\": [\"npm run verify\"],\n \"skills\": []\n },\n {\n \"name\": \"domains-tenants\",\n \"root\": \"domains/tenants\",\n \"kind\": \"core\",\n \"responsibility\": \"Owns the tenant HTTP surface.\",\n \"allowedDependencies\": [\n \"@dads-framework/access\",\n \"@dads-framework/audit\",\n \"@dads-framework/client\",\n \"@dads-framework/core\",\n \"@dads-framework/feature-flags\",\n \"@dads-framework/http\",\n \"@dads-framework/identity\",\n \"@dads-framework/postgres\",\n \"@dads-framework/postgres-access\",\n \"@dads-framework/ui\",\n \"drizzle-orm\",\n \"node-pg-migrate\",\n \"tsx\",\n \"zod\"\n ],\n \"verification\": [\"npm run verify\"],\n \"skills\": []\n },\n {\n \"name\": \"libraries-app-runtime\",\n \"root\": \"libraries/app-runtime\",\n \"kind\": \"core\",\n \"responsibility\": \"Holds the app runtime service token and account types.\",\n \"allowedDependencies\": [\n \"@dads-framework/access\",\n \"@dads-framework/audit\",\n \"@dads-framework/core\",\n \"@dads-framework/feature-flags\",\n \"@dads-framework/http\",\n \"@dads-framework/identity\",\n \"@dads-framework/postgres\",\n \"@dads-framework/postgres-access\",\n \"drizzle-orm\",\n \"node-pg-migrate\",\n \"tsx\",\n \"zod\"\n ],\n \"verification\": [\"npm run verify\"],\n \"skills\": []\n },\n {\n \"name\": \"domains-support\",\n \"root\": \"domains/support\",\n \"kind\": \"core\",\n \"responsibility\": \"Owns the staff impersonation HTTP surface.\",\n \"allowedDependencies\": [\"@dads-framework/identity\", \"zod\"],\n \"verification\": [\"npm run verify\"],\n \"skills\": []\n },\n {\n \"name\": \"libraries-sign-in-options\",\n \"root\": \"libraries/sign-in-options\",\n \"kind\": \"core\",\n \"responsibility\": \"Owns the sign-in availability route contract.\",\n \"allowedDependencies\": [\"@dads-framework/core\", \"zod\"],\n \"verification\": [\"npm run verify\"],\n \"skills\": []\n },\n {\n \"name\": \"migrations\",\n \"root\": \"migrations\",\n \"kind\": \"binding\",\n \"responsibility\": \"Installs the app schema and audit triggers.\",\n \"allowedDependencies\": [\n \"@dads-framework/access\",\n \"@dads-framework/audit\",\n \"@dads-framework/core\",\n \"@dads-framework/feature-flags\",\n \"@dads-framework/http\",\n \"@dads-framework/identity\",\n \"@dads-framework/postgres\",\n \"@dads-framework/postgres-access\",\n \"drizzle-orm\",\n \"node-pg-migrate\",\n \"tsx\",\n \"zod\"\n ],\n \"verification\": [\"npm run verify\"],\n \"skills\": []\n }\n ],\n \"domainBoundaries\": {\n \"domains\": [\"src/domains/*\", \"domains/*\"],\n \"libraries\": [\"libraries/*\"],\n \"workflows\": [\"workflows/*\"],\n \"integrations\": [\"integrations/*\"],\n \"composition\": [\"src/composition\", \"apps/*\", \"assembly\"]\n }\n}\n" },
|
|
61
|
-
{ path: "domains/notes/access/index.ts", content: "import { fromParam, requires } from \"@dads-framework/http\";\nimport { tenantAccess } from \"../../../libraries/app-runtime/index.js\";\n\nexport const notesPermission = tenantAccess.tenant.permissions.view;\n\n/** Notes are visible only inside a tenant the account can view. */\nexport const notesAccess = requires(notesPermission, fromParam(\"tenantId\"));\n" },
|
|
61
|
+
{ path: "domains/notes/access/index.ts", content: "import { fromParam, requires } from \"@dads-framework/http\";\nimport { tenantAccess } from \"../../../libraries/app-runtime/index.js\";\nimport { noteIdSchema } from \"../contract/wire.js\";\n\n/** Notes inherit visibility from their parent tenant and require a branded NoteId. */\nexport const note = tenantAccess.tenant.child(\"note\", {\n id: noteIdSchema,\n inherit: [\"view\"],\n});\n\nexport const notesPermission = tenantAccess.tenant.permissions.view;\n\n/** Notes are visible only inside a tenant the account can view. */\nexport const notesAccess = requires(notesPermission, fromParam(\"tenantId\"));\n" },
|
|
62
|
+
{ path: "domains/notes/access/note-access.test.ts", content: "import { compileAccess, emitZed } from \"@dads-framework/access\";\nimport { createAccessClient } from \"@dads-framework/access/runtime\";\nimport { FakeAuthorization } from \"@dads-framework/access/testing\";\nimport { mintEntityId } from \"@dads-framework/core/contract\";\nimport { tenantIdSchema } from \"@dads-framework/identity/tenants\";\nimport { describe, expect, expectTypeOf, it } from \"vitest\";\n\nimport { account, accountAccess, tenantAccess } from \"../../../libraries/app-runtime/index.js\";\nimport { noteIdSchema, type NoteId } from \"../contract/wire.js\";\nimport { note } from \"./index.js\";\n\ndescribe(\"note access resource\", () => {\n it(\"enforces branded NoteId on note(id) and compiles under tenant\", () => {\n const noteId = mintEntityId(noteIdSchema);\n const tenantId = tenantIdSchema.parse(\"0194f4a0-1234-7000-8000-000000000002\");\n const noteRef = note(noteId);\n const tenantRef = tenantAccess.tenant(tenantId);\n\n expectTypeOf(noteRef.id).toEqualTypeOf<NoteId>();\n expectTypeOf(note).parameter(0).toEqualTypeOf<NoteId>();\n expect(note.idSchema).toBe(noteIdSchema);\n expect(noteRef.id).toBe(noteId);\n expect(noteRef.view.resource).toEqual({ type: \"note\", id: noteId });\n expect(tenantRef.id).toBe(tenantId);\n\n const model = compileAccess([accountAccess, tenantAccess.tenant, note], {\n allowLookupResourcesOn: [tenantAccess.tenant],\n });\n const zed = emitZed(model);\n expect(zed).toContain(\"definition note {\");\n expect(zed).toContain(\"relation tenant: tenants/tenant\");\n expect(zed).toContain(\"permission view = tenant->view\");\n });\n\n it(\"links a branded note to its parent tenant and denies unrelated accounts\", async () => {\n const noteId = mintEntityId(noteIdSchema);\n const tenantId = tenantIdSchema.parse(\"0194f4a0-1234-7000-8000-000000000002\");\n const fake = new FakeAuthorization({\n [tenantAccess.tenant.wireName]: { view: [\"member\"] },\n });\n const client = createAccessClient(fake);\n\n await client.add(tenantAccess.tenant(tenantId), note(noteId).tenant);\n await client.add(account(\"member-1\"), tenantAccess.tenant(tenantId).member);\n\n expect(await client.can(account(\"member-1\"), tenantAccess.tenant(tenantId).view)).toBe(true);\n expect(await client.can(account(\"outsider-1\"), tenantAccess.tenant(tenantId).view)).toBe(false);\n expect(await client.listDirect(note(noteId).tenant)).toEqual([\n { type: tenantAccess.tenant.wireName, id: tenantId },\n ]);\n });\n});\n" },
|
|
62
63
|
{ path: "domains/notes/contract/index.ts", content: "import { tenantIdSchema } from \"@dads-framework/identity/tenants\";\nimport { z } from \"zod\";\n\nexport * from \"./wire.js\";\n\nexport const inTenant = z.object({ tenantId: tenantIdSchema });\n" },
|
|
63
|
-
{ path: "domains/notes/contract/wire.ts", content: "import {
|
|
64
|
+
{ path: "domains/notes/contract/wire.ts", content: "import {\n entityIdSchema,\n getOperation,\n listOperation,\n paginationQuerySchema,\n postOperation,\n} from \"@dads-framework/core/contract\";\nimport { z } from \"zod\";\n\nexport const noteIdSchema = entityIdSchema(\"NoteId\", \"Note identifier.\");\nexport type NoteId = z.infer<typeof noteIdSchema>;\n\nexport const noteInput = z.object({ text: z.string().trim().min(1).max(2000) });\nexport const note = noteInput.extend({\n id: noteIdSchema,\n tenantId: z.uuid(),\n});\n\nexport const notesExport = \"notes.export\";\n\nexport const noteFeatures = z.object({\n features: z.array(z.string()),\n stateHash: z.string(),\n});\n\nexport const noteExportFormat = z.enum([\"csv\", \"pdf\"]);\nexport const noteExportFile = z.strictObject({\n contentType: z.enum([\"application/pdf\", \"text/csv\"]),\n base64: z.base64(),\n});\n\nconst tenantPathParams = z.object({ tenantId: z.uuid() });\nexport const noteIdParamSchema = tenantPathParams.extend({\n noteId: noteIdSchema,\n});\nconst noteExportParams = noteIdParamSchema.extend({\n format: noteExportFormat,\n});\n\nexport const readNoteFeaturesOp = getOperation({\n path: \"/tenants/:tenantId/notes/features\",\n params: tenantPathParams,\n response: noteFeatures,\n});\n\nexport const listNotesOp = listOperation({\n path: \"/tenants/:tenantId/notes\",\n params: tenantPathParams,\n query: paginationQuerySchema,\n item: note,\n});\n\nexport const createNoteOp = postOperation({\n path: \"/tenants/:tenantId/notes\",\n params: tenantPathParams,\n body: noteInput,\n response: note,\n});\n\nexport const exportNoteOp = getOperation({\n path: \"/tenants/:tenantId/notes/:noteId/exports/:format\",\n params: noteExportParams,\n response: noteExportFile,\n});\n" },
|
|
64
65
|
{ path: "domains/notes/copy/flag-metadata.ts", content: "import { defineCopy } from \"@dads-framework/ui/copy\";\n\nexport const noteFlagCopy = defineCopy({\n \"notes.export.description\": {\n en: \"Advertise whether the notes export capability is available.\",\n },\n});\n" },
|
|
65
|
-
{ path: "domains/notes/index.ts", content: "export { notesAttachmentWorker, notesPlugin } from \"./server/plugin.js\";\n" },
|
|
66
|
-
{ path: "domains/notes/pure/note-rules.test.ts", content: "import { describe, expect, it } from \"vitest\";\nimport { buildNoteExportFilename, createNoteRecord, escapeCsvFormulaCell, normalizeNoteText } from \"./note-rules.js\";\n\ndescribe(\"note-rules\", () => {\n it(\"normalizes whitespace and line endings deterministically\", () => {\n expect(normalizeNoteText(\" first line\\r\\nsecond line\\rthird line \")).toBe(\"first line\\nsecond line\\nthird line\");\n expect(normalizeNoteText(\"\\n single line \\t\")).toBe(\"single line\");\n });\n\n it(\"creates a normalized note record from explicit inputs\", () => {\n const
|
|
67
|
-
{ path: "domains/notes/pure/note-rules.ts", content: "
|
|
68
|
-
{ path: "domains/notes/server/attachments.ts", content: "import { createHash, randomUUID } from \"node:crypto\";\nimport { notFound } from \"@dads-framework/core/errors\";\nimport { getRoute, routeGroup, postRoute } from \"@dads-framework/http\";\nimport { defineJob } from \"@dads-framework/job-queue/core\";\nimport { and, eq } from \"drizzle-orm\";\nimport { z } from \"zod\";\n\nimport type { StarterServices } from \"../../../libraries/app-runtime/index.js\";\nimport { notesAccess, notesPermission } from \"../access/index.js\";\nimport { inTenant } from \"../contract/index.js\";\nimport { noteTable } from \"./tables.js\";\n\ntype Files = Pick<StarterServices, \"files\" | \"jobs\" | \"writeWithPermission\">;\nconst attachmentJobName = \"notes.inspect-attachment\";\nconst notePath = inTenant.extend({ noteId:
|
|
66
|
+
{ path: "domains/notes/index.ts", content: "export { noteIdSchema, type NoteId } from \"./contract/index.js\";\nexport { notesAttachmentWorker, notesPlugin } from \"./server/plugin.js\";\n" },
|
|
67
|
+
{ path: "domains/notes/pure/note-rules.test.ts", content: "import { mintEntityId } from \"@dads-framework/core/contract\";\nimport { describe, expect, it } from \"vitest\";\nimport { noteIdSchema } from \"../contract/wire.js\";\nimport { buildNoteExportFilename, createNoteRecord, escapeCsvFormulaCell, normalizeNoteText } from \"./note-rules.js\";\n\ndescribe(\"note-rules\", () => {\n it(\"normalizes whitespace and line endings deterministically\", () => {\n expect(normalizeNoteText(\" first line\\r\\nsecond line\\rthird line \")).toBe(\"first line\\nsecond line\\nthird line\");\n expect(normalizeNoteText(\"\\n single line \\t\")).toBe(\"single line\");\n });\n\n it(\"creates a normalized note record from explicit inputs\", () => {\n const id = noteIdSchema.parse(\"0194f4a0-1234-7000-8000-000000000001\");\n const record = createNoteRecord({\n id,\n tenantId: \"0194f4a0-1234-7000-8000-000000000002\",\n text: \" Hello\\r\\nworld \",\n });\n expect(record).toEqual({\n id,\n tenantId: \"0194f4a0-1234-7000-8000-000000000002\",\n text: \"Hello\\nworld\",\n });\n });\n\n it(\"accepts freshly minted UUIDv7 note ids\", () => {\n const id = mintEntityId(noteIdSchema);\n const record = createNoteRecord({\n id,\n tenantId: \"0194f4a0-1234-7000-8000-000000000002\",\n text: \" Fresh note \",\n });\n expect(record.id).toBe(id);\n expect(noteIdSchema.safeParse(record.id).success).toBe(true);\n expect(record.text).toBe(\"Fresh note\");\n });\n\n it(\"escapes CSV formula prefixes and preserves ordinary text\", () => {\n expect(escapeCsvFormulaCell(\"=SUM(A1:A2)\")).toBe(\"'=SUM(A1:A2)\");\n expect(escapeCsvFormulaCell(\" +1+1\")).toBe(\"' +1+1\");\n expect(escapeCsvFormulaCell(\"-cmd\")).toBe(\"'-cmd\");\n expect(escapeCsvFormulaCell(\"@mention\")).toBe(\"'@mention\");\n expect(escapeCsvFormulaCell(\"Alpha's note\")).toBe(\"Alpha's note\");\n });\n\n it(\"builds deterministic export filenames\", () => {\n expect(buildNoteExportFilename(\"0194F4A0-1234-7000-8000-000000000001\", \"csv\")).toBe(\"note-0194f4a0.csv\");\n expect(buildNoteExportFilename(\"0194F4A0-1234-7000-8000-000000000001\", \"pdf\")).toBe(\"note-0194f4a0.pdf\");\n expect(buildNoteExportFilename(\" --- \", \"csv\")).toBe(\"note.csv\");\n });\n});\n" },
|
|
68
|
+
{ path: "domains/notes/pure/note-rules.ts", content: "import type { NoteId } from \"../contract/wire.js\";\n\nexport type NoteExportFormat = \"csv\" | \"pdf\";\n\nexport type NoteRecord = {\n readonly id: NoteId;\n readonly tenantId: string;\n readonly text: string;\n};\n\n/** Normalize line endings and surrounding whitespace before persisting a note. */\nexport function normalizeNoteText(text: string): string {\n return text.replace(/\\r\\n?/gu, \"\\n\").trim();\n}\n\n/** Build a normalized note record from explicit inputs without ambient ID or clock access. */\nexport function createNoteRecord(input: {\n readonly id: NoteId;\n readonly tenantId: string;\n readonly text: string;\n}): NoteRecord {\n return {\n id: input.id,\n tenantId: input.tenantId,\n text: normalizeNoteText(input.text),\n };\n}\n\n/** Neutralize spreadsheet formula prefixes before serializing note text to CSV. */\nexport function escapeCsvFormulaCell(text: string): string {\n return /^[\\s]*[=+\\-@]/u.test(text) ? `'${text}` : text;\n}\n\n/** Build a deterministic, filesystem-safe download filename for a note export. */\nexport function buildNoteExportFilename(noteId: string, format: NoteExportFormat): string {\n const shortId = noteId\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]/gu, \"\")\n .slice(0, 8);\n const stem = shortId.length > 0 ? `note-${shortId}` : \"note\";\n return `${stem}.${format}`;\n}\n" },
|
|
69
|
+
{ path: "domains/notes/server/attachments.ts", content: "import { createHash, randomUUID } from \"node:crypto\";\nimport { notFound } from \"@dads-framework/core/errors\";\nimport { getRoute, routeGroup, postRoute } from \"@dads-framework/http\";\nimport { defineJob } from \"@dads-framework/job-queue/core\";\nimport { and, eq } from \"drizzle-orm\";\nimport { z } from \"zod\";\n\nimport type { StarterServices } from \"../../../libraries/app-runtime/index.js\";\nimport { notesAccess, notesPermission } from \"../access/index.js\";\nimport { inTenant, noteIdSchema } from \"../contract/index.js\";\nimport { noteTable } from \"./tables.js\";\n\ntype Files = Pick<StarterServices, \"files\" | \"jobs\" | \"writeWithPermission\">;\nconst attachmentJobName = \"notes.inspect-attachment\";\nconst notePath = inTenant.extend({ noteId: noteIdSchema });\nconst filePath = notePath.extend({ fileId: z.uuid() });\nconst digest = z.strictObject({\n bytes: z.number().int(),\n sha256: z.string().length(64),\n});\n\nexport function noteAttachmentJobs({ files }: Pick<StarterServices, \"files\">) {\n return [\n defineJob({\n name: attachmentJobName,\n payload: filePath,\n retry: { attempts: 3, backoffMs: 300 },\n schedules: [],\n run: async (params) => {\n const key = objectKey(params);\n const stored = await files.get(key);\n if (!stored) return;\n const facts = {\n bytes: stored.body.byteLength,\n sha256: createHash(\"sha256\").update(stored.body).digest(\"hex\"),\n };\n await files.put(`${key}.facts`, JSON.stringify(facts), \"application/json\");\n },\n }),\n ];\n}\n\nexport function noteAttachmentRoutes(services: Files) {\n return routeGroup(\"Notes\", [\n postRoute({\n route: {\n method: \"POST\",\n template: \"/tenants/:tenantId/notes/:noteId/attachments\",\n },\n summary: \"Attach a short UTF-8 text file to a note\",\n access: notesAccess,\n params: notePath,\n body: z.strictObject({ text: z.string().min(1).max(16_384) }),\n response: z.strictObject({ fileId: z.uuid() }),\n handler: ({ body, params, subject }) => storeNoteAttachment(services, params, subject, body.text),\n }),\n getRoute({\n route: {\n method: \"GET\",\n template: \"/tenants/:tenantId/notes/:noteId/attachments/:fileId\",\n },\n summary: \"Read a note attachment and its inspected byte digest\",\n access: notesAccess,\n params: filePath,\n response: z.strictObject({\n text: z.string(),\n inspection: digest.nullable(),\n }),\n handler: ({ params }) => readNoteAttachment(services, params),\n }),\n ]);\n}\n\nasync function storeNoteAttachment(\n { files, jobs, writeWithPermission }: Files,\n params: z.infer<typeof notePath>,\n subject: Parameters<StarterServices[\"writeWithPermission\"]>[0][\"subject\"],\n text: string,\n) {\n const fileId = randomUUID();\n const uploaded = { ...params, fileId };\n const key = objectKey(uploaded);\n try {\n await writeWithPermission({ subject, permission: notesPermission, resourceId: params.tenantId }, async (tx) => {\n const [note] = await tx\n .select({ id: noteTable.id })\n .from(noteTable)\n .where(and(eq(noteTable.id, params.noteId), eq(noteTable.tenantId, params.tenantId)))\n .limit(1);\n if (!note) throw notFound(\"NOT_FOUND\", \"Note not found\");\n await files.put(key, text, \"text/plain\");\n });\n } catch (error) {\n await files.delete(key).catch(() => undefined);\n throw error;\n }\n await jobs.enqueue(attachmentJobName, uploaded);\n return { fileId };\n}\n\nasync function readNoteAttachment({ files }: Files, params: z.infer<typeof filePath>) {\n const key = objectKey(params);\n const [stored, inspected] = await Promise.all([files.get(key), files.get(`${key}.facts`)]);\n if (!stored) throw notFound(\"NOT_FOUND\", \"Attachment not found\");\n const decode = new TextDecoder();\n return {\n text: decode.decode(stored.body),\n inspection: inspected ? digest.parse(JSON.parse(decode.decode(inspected.body))) : null,\n };\n}\n\nfunction objectKey({ tenantId, noteId, fileId }: z.infer<typeof filePath>): string {\n return `notes/${tenantId}/${noteId}/${fileId}`;\n}\n" },
|
|
69
70
|
{ path: "domains/notes/server/exports.ts", content: "import { toCsv } from \"@dads-framework/documents/csv\";\nimport { notFound } from \"@dads-framework/core/errors\";\nimport { getRoute, routeGroup } from \"@dads-framework/http\";\nimport { createPdfRenderer } from \"@dads-framework/documents/pdf\";\nimport { and, eq } from \"drizzle-orm\";\n\nimport type { StarterServices } from \"../../../libraries/app-runtime/index.js\";\nimport { notesAccess } from \"../access/index.js\";\nimport { exportNoteOp } from \"../contract/index.js\";\nimport { escapeCsvFormulaCell } from \"../pure/note-rules.js\";\nimport { notesExportFlag } from \"./flags.js\";\nimport { noteTable } from \"./tables.js\";\n\nexport function noteExportRoutes({ db, flags }: Pick<StarterServices, \"db\" | \"flags\">) {\n const pdf = createPdfRenderer();\n return routeGroup(\"Notes\", [\n getRoute({\n operation: exportNoteOp,\n summary: \"Generate a CSV or PDF copy of a note\",\n access: notesAccess,\n handler: async ({ params }) => {\n const state = await flags.execute({\n kind: \"tenant\",\n tenantId: params.tenantId,\n });\n if (!state.features.includes(notesExportFlag.slug)) throw notFound(\"NOT_FOUND\", \"Note export not available\");\n const [note] = await db\n .select({ text: noteTable.text })\n .from(noteTable)\n .where(and(eq(noteTable.id, params.noteId), eq(noteTable.tenantId, params.tenantId)))\n .limit(1);\n if (!note) throw notFound(\"NOT_FOUND\", \"Note not found\");\n return params.format === \"csv\" ? csvExport(note.text) : pdfExport(pdf, note.text);\n },\n }),\n ]);\n}\n\nfunction csvExport(text: string): { readonly contentType: \"text/csv\"; readonly base64: string } {\n const csv = toCsv([{ text: escapeCsvFormulaCell(text) }], [{ key: \"text\", header: \"Note\" }]);\n return {\n contentType: \"text/csv\",\n base64: Buffer.from(csv).toString(\"base64\"),\n };\n}\n\nasync function pdfExport(\n pdf: ReturnType<typeof createPdfRenderer>,\n text: string,\n): Promise<{ readonly contentType: \"application/pdf\"; readonly base64: string }> {\n return {\n contentType: \"application/pdf\",\n base64: Buffer.from(await pdf.render({ content: [\"Note\", text] })).toString(\"base64\"),\n };\n}\n" },
|
|
70
71
|
{ path: "domains/notes/server/flags.ts", content: "import { defineFeatureFlag } from \"@dads-framework/feature-flags\";\nimport { notesExport } from \"../contract/index.js\";\nimport { noteFlagCopy } from \"../copy/flag-metadata.js\";\n\nexport const notesExportFlag = defineFeatureFlag({\n slug: notesExport,\n name: \"Notes export\",\n description: noteFlagCopy[\"notes.export.description\"].en,\n owner: \"Notes\",\n defaultEnabled: false,\n affectedPages: [],\n affectedApiCapabilities: [notesExport],\n cleanupTrigger: \"The export capability reaches every tenant.\",\n globalStabilityDays: 14,\n});\n" },
|
|
71
72
|
{ path: "domains/notes/server/notes-store.ts", content: "import type { DrizzleHandle } from \"@dads-framework/postgres\";\nimport { count, eq } from \"drizzle-orm\";\nimport type { NoteRecord } from \"../pure/note-rules.js\";\nimport { noteTable } from \"./tables.js\";\n\nexport type { NoteRecord } from \"../pure/note-rules.js\";\n\nexport type ListTenantNotesInput = {\n readonly tenantId: string;\n readonly page: number;\n readonly perPage: number;\n};\n\nexport type ListTenantNotesResult = {\n readonly items: readonly NoteRecord[];\n readonly total: number;\n};\n\nexport type NoteWriteTransaction = Parameters<Parameters<DrizzleHandle[\"transaction\"]>[0]>[0];\n\nexport type NotesStore = {\n listNotes(input: ListTenantNotesInput): Promise<ListTenantNotesResult>;\n insertNote(tx: NoteWriteTransaction, value: NoteRecord): Promise<NoteRecord>;\n};\n\nexport async function listTenantNotes(\n db: DrizzleHandle,\n { tenantId, page, perPage }: ListTenantNotesInput,\n): Promise<ListTenantNotesResult> {\n const scope = eq(noteTable.tenantId, tenantId);\n const [rows, totals] = await Promise.all([\n db\n .select()\n .from(noteTable)\n .where(scope)\n .orderBy(noteTable.id)\n .limit(perPage)\n .offset((page - 1) * perPage),\n db.select({ total: count() }).from(noteTable).where(scope),\n ]);\n return {\n items: rows.map((row) => ({\n id: row.id,\n text: row.text,\n tenantId: row.tenantId,\n })),\n total: totals[0]?.total ?? 0,\n };\n}\n\nexport async function insertTenantNote(tx: NoteWriteTransaction, value: NoteRecord): Promise<NoteRecord> {\n await tx.insert(noteTable).values(value);\n return value;\n}\n\nexport function createNotesStore(db: DrizzleHandle): NotesStore {\n return {\n listNotes: (input) => listTenantNotes(db, input),\n insertNote: (tx, value) => insertTenantNote(tx, value),\n };\n}\n" },
|
|
72
|
-
{ path: "domains/notes/server/plugin.ts", content: "import { definePlugin } from \"@dads-framework/core/plugin\";\nimport {\n databaseService,\n featureFlagsService,\n jobQueueService,\n objectStorageService,\n protectedWriteService,\n} from \"../../../libraries/app-runtime/index.js\";\nimport { noteAttachmentJobs, noteAttachmentRoutes } from \"./attachments.js\";\nimport { noteExportRoutes } from \"./exports.js\";\nimport { notesExportFlag } from \"./flags.js\";\nimport { notesRoutes } from \"./routes.js\";\n\nexport const notesPlugin = definePlugin({\n name: \"notes\",\n requires: [databaseService, featureFlagsService, objectStorageService, jobQueueService, protectedWriteService],\n contributes: { flags: [notesExportFlag] },\n setup: ({ use }) => {\n const db = use(databaseService);\n const flags = use(featureFlagsService);\n const files = use(objectStorageService);\n const jobs = use(jobQueueService);\n const writeWithPermission = use(protectedWriteService);\n return {\n routes: [\n ...notesRoutes({ db, flags, writeWithPermission }),\n ...noteAttachmentRoutes({ files, jobs, writeWithPermission }),\n ...noteExportRoutes({ db, flags }),\n ],\n };\n },\n});\n\nexport const notesAttachmentWorker = definePlugin({\n name: \"notes-attachment-worker\",\n requires: [objectStorageService],\n setup: ({ use }) => ({ jobs: noteAttachmentJobs({ files: use(objectStorageService) }) }),\n});\n" },
|
|
73
|
-
{ path: "domains/notes/server/routes.ts", content: "import {
|
|
74
|
-
{ path: "domains/notes/server/tables.ts", content: "import { pgTable, text, uuid } from \"drizzle-orm/pg-core\";\n\nexport const noteTable = pgTable(\"starter_note\", {\n id: uuid().primaryKey(),\n tenantId: uuid(\"tenant_id\").notNull(),\n text: text().notNull(),\n});\n" },
|
|
75
|
-
{ path: "domains/notes/web-client/index.ts", content: "import { createApiClient } from \"@dads-framework/client\";\nimport type { z } from \"zod\";\nimport {\n createNoteOp,\n exportNoteOp,\n listNotesOp,\n readNoteFeaturesOp,\n type note,\n type noteExportFormat,\n} from \"../contract/wire.js\";\n\nexport type Note = z.output<typeof note>;\nexport type NoteExportFormat = z.output<typeof noteExportFormat>;\nexport { notesExport } from \"../contract/wire.js\";\n\nexport const notesClient = createApiClient({\n list: listNotesOp,\n readFeatures: readNoteFeaturesOp,\n create: createNoteOp,\n exportFile: exportNoteOp,\n});\n\nexport function listNotes(tenantId: string, page: number, signal: AbortSignal) {\n return notesClient.list({\n params: { tenantId },\n query: { page, perPage: 12 },\n signal,\n });\n}\n\nexport function readFeatures(tenantId: string, signal: AbortSignal) {\n return notesClient.readFeatures({\n params: { tenantId },\n signal,\n });\n}\n\nexport function createNote(tenantId: string, text: string) {\n return notesClient.create({\n params: { tenantId },\n body: { text },\n });\n}\n\nexport function exportNote(tenantId: string, noteId:
|
|
73
|
+
{ path: "domains/notes/server/plugin.ts", content: "import type { DslNode } from \"@dads-framework/access\";\nimport { definePlugin } from \"@dads-framework/core/plugin\";\nimport {\n databaseService,\n featureFlagsService,\n jobQueueService,\n objectStorageService,\n protectedWriteService,\n} from \"../../../libraries/app-runtime/index.js\";\nimport { note } from \"../access/index.js\";\nimport { noteAttachmentJobs, noteAttachmentRoutes } from \"./attachments.js\";\nimport { noteExportRoutes } from \"./exports.js\";\nimport { notesExportFlag } from \"./flags.js\";\nimport { notesRoutes } from \"./routes.js\";\n\nconst noteAccessNodes: readonly DslNode[] = [note];\n\nexport const notesPlugin = definePlugin({\n name: \"notes\",\n requires: [databaseService, featureFlagsService, objectStorageService, jobQueueService, protectedWriteService],\n contributes: { access: noteAccessNodes, flags: [notesExportFlag] },\n setup: ({ use }) => {\n const db = use(databaseService);\n const flags = use(featureFlagsService);\n const files = use(objectStorageService);\n const jobs = use(jobQueueService);\n const writeWithPermission = use(protectedWriteService);\n return {\n routes: [\n ...notesRoutes({ db, flags, writeWithPermission }),\n ...noteAttachmentRoutes({ files, jobs, writeWithPermission }),\n ...noteExportRoutes({ db, flags }),\n ],\n };\n },\n});\n\nexport const notesAttachmentWorker = definePlugin({\n name: \"notes-attachment-worker\",\n requires: [objectStorageService],\n setup: ({ use }) => ({ jobs: noteAttachmentJobs({ files: use(objectStorageService) }) }),\n});\n" },
|
|
74
|
+
{ path: "domains/notes/server/routes.ts", content: "import { mintEntityId } from \"@dads-framework/core/contract\";\nimport { getRoute, listRoute, postRoute, routeGroup } from \"@dads-framework/http\";\nimport type { StarterServices } from \"../../../libraries/app-runtime/index.js\";\nimport { notesAccess, notesPermission } from \"../access/index.js\";\nimport { createNoteOp, listNotesOp, noteIdSchema, readNoteFeaturesOp } from \"../contract/index.js\";\nimport { createNoteRecord } from \"../pure/note-rules.js\";\nimport { createNotesStore } from \"./notes-store.js\";\n\nexport function notesRoutes({\n db,\n flags,\n writeWithPermission,\n}: Pick<StarterServices, \"db\" | \"flags\" | \"writeWithPermission\">) {\n const notesStore = createNotesStore(db);\n\n return routeGroup(\"Notes\", [\n getRoute({\n operation: readNoteFeaturesOp,\n summary: \"Read feature availability for a tenant\",\n access: notesAccess,\n handler: ({ params }) => flags.execute({ kind: \"tenant\", tenantId: params.tenantId }),\n }),\n listRoute({\n operation: listNotesOp,\n summary: \"Read notes in a tenant\",\n access: notesAccess,\n handler: ({ params, query }) =>\n notesStore.listNotes({\n tenantId: params.tenantId,\n page: query.page,\n perPage: query.perPage,\n }),\n }),\n postRoute({\n operation: createNoteOp,\n summary: \"Create a note in a tenant\",\n access: notesAccess,\n handler: ({ body, params, subject }) => {\n const value = createNoteRecord({\n id: mintEntityId(noteIdSchema),\n tenantId: params.tenantId,\n text: body.text,\n });\n return writeWithPermission({ subject, permission: notesPermission, resourceId: params.tenantId }, (tx) =>\n notesStore.insertNote(tx, value),\n );\n },\n }),\n ]);\n}\n" },
|
|
75
|
+
{ path: "domains/notes/server/tables.ts", content: "import { pgTable, text, uuid } from \"drizzle-orm/pg-core\";\nimport type { NoteId } from \"../contract/wire.js\";\n\nexport const noteTable = pgTable(\"starter_note\", {\n id: uuid().primaryKey().$type<NoteId>(),\n tenantId: uuid(\"tenant_id\").notNull(),\n text: text().notNull(),\n});\n" },
|
|
76
|
+
{ path: "domains/notes/web-client/index.ts", content: "import { createApiClient } from \"@dads-framework/client\";\nimport type { z } from \"zod\";\nimport {\n createNoteOp,\n exportNoteOp,\n listNotesOp,\n readNoteFeaturesOp,\n type note,\n type noteExportFormat,\n type NoteId,\n} from \"../contract/wire.js\";\n\nexport type Note = z.output<typeof note>;\nexport type NoteExportFormat = z.output<typeof noteExportFormat>;\nexport type { NoteId } from \"../contract/wire.js\";\nexport { notesExport } from \"../contract/wire.js\";\n\nexport const notesClient = createApiClient({\n list: listNotesOp,\n readFeatures: readNoteFeaturesOp,\n create: createNoteOp,\n exportFile: exportNoteOp,\n});\n\nexport function listNotes(tenantId: string, page: number, signal: AbortSignal) {\n return notesClient.list({\n params: { tenantId },\n query: { page, perPage: 12 },\n signal,\n });\n}\n\nexport function readFeatures(tenantId: string, signal: AbortSignal) {\n return notesClient.readFeatures({\n params: { tenantId },\n signal,\n });\n}\n\nexport function createNote(tenantId: string, text: string) {\n return notesClient.create({\n params: { tenantId },\n body: { text },\n });\n}\n\nexport function exportNote(tenantId: string, noteId: NoteId, format: NoteExportFormat) {\n return notesClient.exportFile({\n params: { tenantId, noteId, format },\n });\n}\n" },
|
|
76
77
|
{ path: "domains/support/contract/configuration.ts", content: "import { tenantIdSchema } from \"@dads-framework/identity/tenants\";\nimport { z } from \"zod\";\n\nconst accountId = z\n .string()\n .trim()\n .min(1)\n .max(256)\n .regex(/^[^\\0]+$/u);\nexport const staffImpersonationConfiguration = z.strictObject({\n tenantId: z\n .string()\n .transform((id) => id.toLowerCase())\n .pipe(tenantIdSchema),\n staffAccountIds: z.array(accountId).min(1),\n revokerAccountIds: z.array(accountId),\n});\n\nexport type StaffImpersonationConfiguration = z.output<typeof staffImpersonationConfiguration>;\n" },
|
|
77
78
|
{ path: "domains/support/index.ts", content: "export { staffImpersonationConfiguration, type StaffImpersonationConfiguration } from \"./contract/configuration.js\";\nexport { configureStaffImpersonation, readTenantAsTarget } from \"./server/impersonation.js\";\n" },
|
|
78
79
|
{ path: "domains/support/server/impersonation.ts", content: "import { TenantUnavailableError, type TenantId, type Tenants } from \"@dads-framework/identity/tenants\";\nimport { z } from \"zod\";\n\nimport type { Impersonation } from \"@dads-framework/identity/impersonation\";\n\nconst grant = z.strictObject({ grantId: z.uuid() });\nconst start = z.strictObject({\n effectiveAccountId: z.string().min(1).max(256),\n});\nconst input = z.discriminatedUnion(\"action\", [\n start.extend({ action: z.literal(\"start\") }),\n grant.extend({ action: z.literal(\"view-tenant\") }),\n grant.extend({ action: z.literal(\"stop\") }),\n grant.extend({ action: z.literal(\"revoke\") }),\n]);\n\ntype StaffImpersonationHandlerOptions = {\n readonly baseUrl: string;\n readonly tenantId: TenantId;\n readonly impersonation: Impersonation;\n readonly tenants: Tenants;\n};\n\nexport function configureStaffImpersonation(options: StaffImpersonationHandlerOptions) {\n const trustedOrigin = new URL(options.baseUrl).origin;\n return async function handle(request: Request): Promise<Response> {\n const refused = validateRequest(request, trustedOrigin);\n if (refused !== undefined) return refused;\n const body: unknown = await request.json().catch(() => null);\n const parsed = input.safeParse(body);\n if (!parsed.success) return rejection(400, \"INVALID_REQUEST\");\n return runCommand(options, request.headers, parsed.data);\n };\n}\n\nfunction validateRequest(request: Request, trustedOrigin: string) {\n if (request.method !== \"POST\" || new URL(request.url).pathname !== \"/api/staff/impersonation\") {\n return rejection(404, \"RESOURCE_NOT_FOUND\");\n }\n if (request.headers.get(\"origin\") !== trustedOrigin) {\n return rejection(403, \"UNTRUSTED_ORIGIN\");\n }\n const contentType = request.headers.get(\"content-type\")?.split(\";\")[0]?.trim().toLowerCase();\n if (contentType !== \"application/json\") return rejection(415, \"UNSUPPORTED_MEDIA_TYPE\");\n return undefined;\n}\n\nasync function runCommand(\n options: StaffImpersonationHandlerOptions,\n headers: Headers,\n command: z.output<typeof input>,\n) {\n const { impersonation, tenantId } = options;\n switch (command.action) {\n case \"start\": {\n const issued = await impersonation.start(headers, {\n tenantId,\n effectiveAccountId: command.effectiveAccountId,\n });\n return issued === null ? rejectedGrant() : json(issued, 201);\n }\n case \"view-tenant\":\n return viewTenant(options, headers, command.grantId);\n case \"stop\":\n return (await impersonation.stop(headers, command.grantId)) ? json({ stopped: true }) : rejectedGrant();\n case \"revoke\":\n return (await impersonation.revoke(headers, command.grantId)) ? json({ revoked: true }) : rejectedGrant();\n }\n}\n\nasync function viewTenant(\n { impersonation, tenants, tenantId }: StaffImpersonationHandlerOptions,\n headers: Headers,\n grantId: string,\n) {\n const active = await impersonation.use(headers, { grantId, tenantId });\n if (active === null) return rejectedGrant();\n const view = await readTenantAsTarget(tenants, active.effectiveAccountId, tenantId);\n return view === null\n ? rejectedGrant()\n : json({\n staffAccountId: active.staffAccountId,\n effectiveAccountId: active.effectiveAccountId,\n tenant: { id: view.id, name: view.name },\n });\n}\n\nexport async function readTenantAsTarget(tenants: Tenants, accountId: string, tenantId: TenantId) {\n try {\n return (await tenants.context(accountId, tenantId)).tenant;\n } catch (error) {\n if (error instanceof TenantUnavailableError) return null;\n throw error;\n }\n}\n\nfunction json(body: unknown, status = 200) {\n return Response.json(body, {\n status,\n headers: { \"cache-control\": \"no-store\" },\n });\n}\n\nfunction rejection(status: number, code: string) {\n return json({ error: { code } }, status);\n}\n\nfunction rejectedGrant() {\n return rejection(404, \"RESOURCE_NOT_FOUND\");\n}\n" },
|
|
@@ -111,7 +112,7 @@ export const kitStarterFiles = [
|
|
|
111
112
|
{ path: "migrations/20261120080300_enterprise_identity.migration.ts", content: "import {\n installIdentityEnterpriseSsoSchema,\n installIdentitySigningKeyMetadataSchema,\n} from \"@dads-framework/identity/better-auth\";\nimport {\n installTenantScimGroupSchemaV1,\n installTenantScimSchemaV1,\n} from \"@dads-framework/identity/tenants\";\nimport type { MigrationBuilder } from \"node-pg-migrate\";\n\nexport function up(pgm: MigrationBuilder): void {\n installIdentitySigningKeyMetadataSchema(pgm);\n installIdentityEnterpriseSsoSchema(pgm);\n installTenantScimSchemaV1(pgm);\n installTenantScimGroupSchemaV1(pgm);\n}\n\n/** Keep provisioned users and enterprise session provenance on rollback. */\nexport const down = false;\n" },
|
|
112
113
|
{ path: "migrations/20261120080400_staff_impersonation.migration.ts", content: "import { installStaffImpersonationSchemaV1 } from \"@dads-framework/identity/better-auth/impersonation-store\";\nimport type { MigrationBuilder } from \"node-pg-migrate\";\n\nexport function up(pgm: MigrationBuilder): void {\n installStaffImpersonationSchemaV1(pgm);\n}\n\n/** Keep the staff impersonation audit trail on rollback. */\nexport const down = false;\n" },
|
|
113
114
|
{ path: "migrations/support/feature-flags.ts", content: "export { installFeatureFlagSchemaV1 } from \"@dads-framework/feature-flags/postgres\";\n" },
|
|
114
|
-
{ path: "package.json", content: "{\n \"name\": \"@dads-fixture/kit-workbench\",\n \"version\": \"0.
|
|
115
|
+
{ path: "package.json", content: "{\n \"name\": \"@dads-fixture/kit-workbench\",\n \"version\": \"0.5.0\",\n \"private\": true,\n \"type\": \"module\",\n \"engines\": {\n \"node\": \">=22\"\n },\n \"scripts\": {\n \"dev\": \"tsx watch assembly/main.ts\",\n \"start\": \"tsx assembly/main.ts\",\n \"migrate\": \"tsx assembly/migrate.ts\",\n \"typecheck\": \"tsc -p tsconfig.json --noEmit\",\n \"test\": \"vitest run\",\n \"verify\": \"npm run typecheck && npm test\",\n \"dev:web\": \"vite --host 127.0.0.1\",\n \"build:web\": \"vite build\",\n \"dev:up\": \"node assembly/dev.mjs up\",\n \"dev:down\": \"node assembly/dev.mjs down\",\n \"dev:mail\": \"node assembly/dev.mjs mail\",\n \"dev:status\": \"node assembly/dev.mjs status\",\n \"dev:restart\": \"node assembly/dev.mjs restart\",\n \"start:api\": \"tsx assembly/main.ts\",\n \"examples:setup\": \"node examples/setup.mjs\"\n },\n \"dependencies\": {\n \"@better-auth/core\": \"1.7.26\",\n \"@better-auth/sso\": \"1.7.26\",\n \"@dads-framework/access\": \"0.5.0\",\n \"@dads-framework/audit\": \"0.5.0\",\n \"@dads-framework/client\": \"0.5.0\",\n \"@dads-framework/core\": \"0.5.0\",\n \"@dads-framework/documents\": \"0.5.0\",\n \"@dads-framework/email\": \"0.5.0\",\n \"@dads-framework/feature-flags\": \"0.5.0\",\n \"@dads-framework/http\": \"0.5.0\",\n \"@dads-framework/identity\": \"0.5.0\",\n \"@dads-framework/job-queue\": \"0.5.0\",\n \"@dads-framework/object-storage\": \"0.5.0\",\n \"@dads-framework/postgres\": \"0.5.0\",\n \"@dads-framework/postgres-access\": \"0.5.0\",\n \"@dads-framework/spicedb-access\": \"0.5.0\",\n \"@dads-framework/ui\": \"0.5.0\",\n \"@opentelemetry/api\": \"^1.9.0\",\n \"@opentelemetry/exporter-trace-otlp-proto\": \"^0.222.0\",\n \"@opentelemetry/instrumentation\": \"^0.222.0\",\n \"@opentelemetry/instrumentation-http\": \"^0.222.0\",\n \"@opentelemetry/instrumentation-pg\": \"^0.74.0\",\n \"@opentelemetry/resources\": \"^2.11.0\",\n \"@opentelemetry/sdk-node\": \"^0.222.0\",\n \"@opentelemetry/sdk-trace\": \"^2.11.0\",\n \"@react-email/components\": \"^1.0.12\",\n \"@react-email/render\": \"^2.1.0\",\n \"better-auth\": \"1.7.26\",\n \"drizzle-orm\": \"^0.45.2\",\n \"kysely\": \"0.28.17\",\n \"node-pg-migrate\": \"^9.0.0\",\n \"pdfmake\": \"^0.3.11\",\n \"react\": \"^19.3.1\",\n \"react-dom\": \"^19.3.1\",\n \"tsx\": \"^4.20.5\",\n \"zod\": \"^4.4.3\"\n },\n \"devDependencies\": {\n \"@dads-framework/testing\": \"0.5.0\",\n \"@dads-framework/toolbox\": \"0.5.0\",\n \"@tailwindcss/vite\": \"^4.3.3\",\n \"@testcontainers/postgresql\": \"^12.0.4\",\n \"@types/node\": \"^24.3.0\",\n \"@types/react\": \"^19.3.0\",\n \"@types/react-dom\": \"^19.3.0\",\n \"marked\": \"15.0.12\",\n \"typescript\": \"6.0.3\",\n \"vite\": \"^8.2.2\",\n \"vitest\": \"^4.1.0\"\n }\n}\n" },
|
|
115
116
|
{ path: "tests/audit-export.test-support.ts", content: "import { expect } from \"vitest\";\nimport { z } from \"zod\";\n\nimport type { startApp } from \"../assembly/start-app.js\";\n\ntype Http = Awaited<ReturnType<typeof startApp>>;\n\nconst auditLine = z.object({\n position: z.int().positive(),\n tableName: z.string(),\n operation: z.enum([\"insert\", \"update\", \"delete\"]),\n});\n\ntype AuditProof = {\n readonly customer: Http;\n readonly staff: Http;\n readonly owner: Record<string, string>;\n readonly member: Record<string, string>;\n readonly tenantId: string;\n readonly otherTenantId: string;\n};\n\nexport async function proveAuditExport(proof: AuditProof) {\n const { customer, staff, owner, member, tenantId, otherTenantId } = proof;\n const url = `/api/tenants/${tenantId}/audit-log/export`;\n const betaNote = await customer.inject({\n method: \"POST\",\n url: `/api/tenants/${otherTenantId}/notes`,\n headers: member,\n payload: { text: \"Beta's private note\" },\n });\n expect(betaNote.statusCode).toBe(201);\n\n await proveAuditExportAccess(proof, url);\n await proveAuditExportPages(staff, url, owner, member);\n await proveAuditExportMetadata(staff, url, owner);\n}\n\nasync function proveAuditExportAccess({ customer, staff, owner, member, otherTenantId }: AuditProof, url: string) {\n expect((await staff.inject({ url })).statusCode).toBe(401);\n expect((await customer.inject({ url, headers: owner })).statusCode).toBe(404);\n const denied = await staff.inject({ url, headers: member });\n expect(denied.statusCode).toBe(404);\n expect(denied.headers[\"content-type\"]).toMatch(/^application\\/json/u);\n expect(\n (\n await staff.inject({\n url: `/api/tenants/${otherTenantId}/audit-log/export`,\n headers: owner,\n })\n ).statusCode,\n ).toBe(404);\n expect((await staff.inject({ url: `${url}?beforePosition=1`, headers: owner })).statusCode).toBe(400);\n}\n\nasync function proveAuditExportPages(\n staff: Http,\n url: string,\n owner: AuditProof[\"owner\"],\n member: AuditProof[\"member\"],\n) {\n const first = await staff.inject({\n url: `${url}?pageSize=1`,\n headers: owner,\n });\n expect(first.statusCode).toBe(200);\n expect(first.headers[\"content-type\"]).toMatch(/^application\\/x-ndjson\\b/u);\n expect(first.headers[\"cache-control\"]).toBe(\"no-store\");\n expect(first.headers[\"content-disposition\"]).toBe('attachment; filename=\"audit-log.ndjson\"');\n const link = first.headers[\"link\"];\n const next = /^<([^>]+)>; rel=\"next\"$/u.exec(typeof link === \"string\" ? link : \"\")?.[1];\n if (next === undefined) throw new Error(\"Expected a continuation link\");\n expect(next.startsWith(`${url}?`)).toBe(true);\n expect((await staff.inject({ url: next, headers: member })).statusCode).toBe(404);\n const nextPage = await staff.inject({ url: next, headers: owner });\n expect(nextPage.statusCode).toBe(200);\n expect(first.body).not.toBe(nextPage.body);\n}\n\nasync function proveAuditExportMetadata(staff: Http, url: string, owner: AuditProof[\"owner\"]) {\n const complete = await staff.inject({ url, headers: owner });\n expect(complete.statusCode).toBe(200);\n const audit = complete.body\n .trimEnd()\n .split(\"\\n\")\n .map((line) => auditLine.parse(JSON.parse(line)));\n expect(audit.filter(({ tableName }) => tableName === \"starter_note\")).toHaveLength(1);\n expect(complete.body).not.toContain(\"rowAfter\");\n expect(complete.body).not.toContain(\"Alpha's note\");\n expect(complete.body).not.toContain(\"Beta's private note\");\n}\n" },
|
|
116
117
|
{ path: "tests/dns-txt.test-support.ts", content: "import { createSocket, type Socket } from \"node:dgram\";\nimport { getServers, setServers } from \"node:dns/promises\";\nimport { syncBuiltinESMExports } from \"node:module\";\n\nconst loopback = \"127.0.0.1\";\nconst headerBytes = 12;\nconst txtIn = Buffer.from([0, 16, 0, 1]);\n\n/** Exercise actual TXT lookups from installed packages, including packed consumers. */\nexport async function withDnsTxtRecord<Result>(\n { name, value }: { name: string; value: string },\n run: () => Promise<Result>,\n): Promise<Result> {\n const question = encodeQuestion(name);\n const answer = encodeAnswer(value);\n const socket = createSocket(\"udp4\");\n socket.on(\"message\", (query, remote) => {\n if (!query.subarray(headerBytes, headerBytes + question.length).equals(question)) return;\n const header = Buffer.alloc(headerBytes);\n query.copy(header, 0, 0, 2); // Transaction ID.\n header.writeUInt16BE(0x8180, 2); // Successful response to a recursive query.\n header.writeUInt16BE(1, 4); // One question.\n header.writeUInt16BE(1, 6); // One answer.\n socket.send([header, question, answer], remote.port, remote.address);\n });\n\n const previousServers = getServers();\n try {\n await listen(socket);\n // setServers replaces the default resolver. Refresh resolved ESM imports\n // so packages that imported resolveTxt before the fixture use that resolver.\n replaceServers([`${loopback}:${String(socket.address().port)}`]);\n return await run();\n } finally {\n try {\n replaceServers(previousServers);\n } finally {\n await new Promise<void>((resolve) => socket.close(resolve));\n }\n }\n}\n\nfunction listen(socket: Socket): Promise<void> {\n return new Promise((resolve, reject) => {\n socket.once(\"error\", reject);\n socket.bind(0, loopback, () => {\n socket.off(\"error\", reject);\n resolve();\n });\n });\n}\n\nfunction encodeQuestion(name: string): Buffer {\n const labels = name.split(\".\").map((label) => Buffer.from(label, \"ascii\"));\n return Buffer.concat([\n ...labels.map((label) => Buffer.concat([Buffer.from([label.length]), label])),\n Buffer.from([0]),\n txtIn,\n ]);\n}\n\nfunction encodeAnswer(text: string): Buffer {\n const value = Buffer.from(text, \"utf8\");\n if (value.length > 255) throw new Error(\"The fixture TXT record is too long.\");\n const data = Buffer.concat([Buffer.from([value.length]), value]);\n const length = Buffer.alloc(2);\n length.writeUInt16BE(data.length);\n return Buffer.concat([\n Buffer.from([0xc0, headerBytes]), // Owner name points to the question.\n txtIn,\n Buffer.alloc(4), // Zero TTL.\n length,\n data,\n ]);\n}\n\nfunction replaceServers(servers: string[]): void {\n setServers(servers);\n syncBuiltinESMExports();\n}\n" },
|
|
117
118
|
{ path: "tests/enterprise-config.test.ts", content: "import { readEnterpriseConfiguration } from \"../assembly/enterprise-config.js\";\nimport { expect, it } from \"vitest\";\n\nit(\"ignores absent configuration and fails closed on incomplete configuration\", () => {\n expect(readEnterpriseConfiguration({})).toEqual({});\n expect(() => readEnterpriseConfiguration({ DADS_ENTERPRISE_SCIM: \"{}\" })).toThrow(\n \"Invalid DADS_ENTERPRISE_SCIM configuration.\",\n );\n expect(() =>\n readEnterpriseConfiguration({\n DADS_ENTERPRISE_SSO_PROVIDERS: \"private fixture text\",\n }),\n ).toThrow(/^Invalid DADS_ENTERPRISE_SSO_PROVIDERS configuration\\.$/u);\n});\n" },
|
|
@@ -121,7 +122,7 @@ export const kitStarterFiles = [
|
|
|
121
122
|
{ path: "tests/local-stack.test.mjs", content: "import { spawnSync } from \"node:child_process\";\nimport { cpSync, existsSync, mkdtempSync, rmSync, statSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport process from \"node:process\";\nimport { fileURLToPath, URL } from \"node:url\";\nimport { afterEach, describe, expect, it } from \"vitest\";\nimport { readLocalState } from \"../assembly/local-state.mjs\";\n\nconst temporary = [];\n\nfunction project() {\n const root = mkdtempSync(join(tmpdir(), \"dads-local-stack-\"));\n temporary.push(root);\n return root;\n}\n\nafterEach(() => {\n for (const root of temporary.splice(0)) rmSync(root, { recursive: true });\n});\n\ndescribe(\"local development state\", () => {\n it(\"only creates state at startup and reuses each project's private secrets\", () => {\n const root = project();\n expect(readLocalState(root, false)).toBeUndefined();\n const initial = readLocalState(root, true);\n expect(initial?.databasePassword).toMatch(/^[a-f0-9]{64}$/);\n expect(initial?.identitySecret).toMatch(/^[a-f0-9]{64}$/);\n expect(initial?.databasePassword).not.toBe(initial?.identitySecret);\n expect(readLocalState(root, true)).toEqual(initial);\n if (process.platform !== \"win32\") {\n expect(statSync(join(root, \".dads/local-dev.json\")).mode & 0o777).toBe(0o600);\n }\n const second = readLocalState(project(), true);\n expect(second?.project).not.toBe(initial?.project);\n expect(second?.databasePassword).not.toBe(initial?.databasePassword);\n });\n\n it(\"reports a missing lockfile before touching Docker or saving secrets\", () => {\n const root = project();\n const assembly = fileURLToPath(new URL(\"../assembly\", import.meta.url));\n cpSync(assembly, join(root, \"assembly\"), { recursive: true });\n const launch = spawnSync(process.execPath, [\"assembly/dev.mjs\", \"up\", \"--json\"], {\n cwd: root,\n encoding: \"utf8\",\n });\n expect(launch.status).toBe(1);\n expect(JSON.parse(launch.stdout)).toEqual({\n ok: false,\n error: \"Run npm install to create package-lock.json before starting the local stack.\",\n });\n expect(existsSync(join(root, \".dads\"))).toBe(false);\n });\n});\n" },
|
|
122
123
|
{ path: "tests/note-artifacts.test-support.ts", content: "import { createHash } from \"node:crypto\";\nimport { expect } from \"vitest\";\nimport { z } from \"zod\";\n\nimport type { startApp } from \"../assembly/start-app.js\";\n\ntype Http = Awaited<ReturnType<typeof startApp>>;\nconst fileResponse = z.object({ data: z.object({ fileId: z.uuid() }) });\nconst exportResponse = z.object({\n data: z.object({ contentType: z.string(), base64: z.base64() }),\n});\n\nexport async function proveNoteArtifacts(\n app: Http,\n note: string,\n allowed: Record<string, string>,\n denied: Record<string, string>,\n): Promise<void> {\n const text = \"UTF-8 résumé\";\n const attachments = `${note}/attachments`;\n const blocked = await app.inject({\n method: \"POST\",\n url: attachments,\n headers: denied,\n payload: { text },\n });\n expect(blocked.statusCode).toBe(404);\n const posted = await app.inject({\n method: \"POST\",\n url: attachments,\n headers: allowed,\n payload: { text },\n });\n expect(posted.statusCode).toBe(201);\n const { fileId } = fileResponse.parse(posted.json()).data;\n const url = `${attachments}/${fileId}`;\n expect((await app.inject({ url, headers: denied })).statusCode).toBe(404);\n await expect\n .poll(async () => {\n const result = await app.inject({ url, headers: allowed });\n return result.json<unknown>();\n })\n .toMatchObject({\n data: {\n text,\n inspection: {\n bytes: Buffer.byteLength(text),\n sha256: createHash(\"sha256\").update(text).digest(\"hex\"),\n },\n },\n });\n await proveExports(app, note, allowed, denied);\n}\n\nasync function proveExports(\n app: Http,\n note: string,\n allowed: Record<string, string>,\n denied: Record<string, string>,\n): Promise<void> {\n const csv = await app.inject({\n url: `${note}/exports/csv`,\n headers: allowed,\n });\n const pdf = await app.inject({\n url: `${note}/exports/pdf`,\n headers: allowed,\n });\n expect(csv.statusCode).toBe(200);\n expect(pdf.statusCode).toBe(200);\n expect(Buffer.from(exportResponse.parse(csv.json()).data.base64, \"base64\").toString()).toContain(\"Alpha's note\");\n expect(Buffer.from(exportResponse.parse(pdf.json()).data.base64, \"base64\").subarray(0, 5).toString()).toBe(\"%PDF-\");\n expect((await app.inject({ url: `${note}/exports/pdf`, headers: denied })).statusCode).toBe(404);\n}\n" },
|
|
123
124
|
{ path: "tests/permissions-dashboard.test-support.ts", content: "import { ACCESS_REFUSAL_HEADER, ACCESS_REFUSAL_VALUE } from \"@dads-framework/core/contract\";\nimport { expect } from \"vitest\";\nimport { z } from \"zod\";\n\nimport type { startApp } from \"../assembly/start-app.js\";\n\ntype Http = Awaited<ReturnType<typeof startApp>>;\ntype RequestHeaders = (cookie?: string) => Record<string, string>;\n\nconst rosterResponse = z.strictObject({\n data: z.array(z.strictObject({ accountId: z.string().min(1), role: z.string() })),\n meta: z.object({ total: z.number() }),\n});\n\nexport async function provePermissionsBeforeInvite(\n http: Http,\n tenantId: string,\n owner: string,\n outsider: string,\n headers: RequestHeaders,\n) {\n const roster = `/api/tenants/${tenantId}/members`;\n const response = await http.inject({\n method: \"GET\",\n url: roster,\n headers: headers(owner),\n });\n expect(response.statusCode).toBe(200);\n const { data } = rosterResponse.parse(response.json());\n expect(data.map(({ role }) => role)).toEqual([\"owner\"]);\n const accountId = data[0]?.accountId;\n if (accountId === undefined) throw new Error(\"Expected a workspace owner.\");\n const permissions = `${roster}/${encodeURIComponent(accountId)}/permissions`;\n const inspected = await http.inject({\n method: \"GET\",\n url: permissions,\n headers: headers(owner),\n });\n expect(inspected.statusCode).toBe(200);\n expect(inspected.json()).toEqual({\n data: {\n role: \"owner\",\n view: true,\n manageMembers: true,\n manageTenant: true,\n },\n });\n for (const url of [roster, permissions]) {\n const denied = await http.inject({\n method: \"GET\",\n url,\n headers: headers(outsider),\n });\n expect(denied.statusCode).toBe(404);\n expect(denied.headers[ACCESS_REFUSAL_HEADER]).toBe(ACCESS_REFUSAL_VALUE);\n expect((await http.inject({ method: \"GET\", url })).statusCode).toBe(401);\n }\n return accountId;\n}\n\nexport async function provePermissionsAfterInvite(\n http: Http,\n tenantId: string,\n owner: string,\n member: string,\n headers: RequestHeaders,\n) {\n const roster = `/api/tenants/${tenantId}/members`;\n const rosterRead = await http.inject({\n method: \"GET\",\n url: roster,\n headers: headers(owner),\n });\n const { data } = rosterResponse.parse(rosterRead.json());\n const selected = data.find(({ role }) => role === \"member\");\n if (selected === undefined) throw new Error(\"Expected an ordinary workspace member.\");\n const url = `${roster}/${encodeURIComponent(selected.accountId)}/permissions`;\n const inspected = await http.inject({\n method: \"GET\",\n url,\n headers: headers(owner),\n });\n expect(inspected.statusCode).toBe(200);\n expect(inspected.json()).toEqual({\n data: {\n role: \"member\",\n view: true,\n manageMembers: false,\n manageTenant: false,\n },\n });\n for (const path of [roster, url]) {\n const denied = await http.inject({\n method: \"GET\",\n url: path,\n headers: headers(member),\n });\n expect(denied.statusCode).toBe(404);\n expect(denied.headers[ACCESS_REFUSAL_HEADER]).toBe(ACCESS_REFUSAL_VALUE);\n }\n}\n" },
|
|
124
|
-
{ path: "tests/protected-write.integration.test.ts", content: "import { randomUUID } from \"node:crypto\";\n\nimport { compileAccess } from \"@dads-framework/access\";\nimport { relationshipWrite } from \"@dads-framework/access/runtime\";\nimport { withSystemActor } from \"@dads-framework/core/audit-actor\";\nimport { createHttpApp, registerRoutes } from \"@dads-framework/http\";\nimport { sql } from \"drizzle-orm\";\nimport { PostgreSqlContainer } from \"@testcontainers/postgresql\";\nimport { expect, it } from \"vitest\";\n\nimport { apiEntrypoints } from \"../assembly/api-entrypoints.js\";\nimport { migrate } from \"../assembly/migrations.js\";\nimport { openServices, provideServices } from \"../assembly/services.js\";\nimport { account, tenantAccess } from \"../libraries/app-runtime/index.js\";\n\nit(\"rechecks permission after the HTTP gate and rolls back data and access together\", { timeout: 90_000 }, async () => {\n const postgres = await new PostgreSqlContainer(\"postgres:16-alpine\").start();\n try {\n const databaseUrl = postgres.getConnectionUri();\n await migrate(databaseUrl);\n const baseUrl = \"http://127.0.0.1:3800\";\n const config = {\n databaseUrl,\n baseUrl,\n secret: \"fixture-signing-key-with-forty-characters\",\n enqueueEmail: () => Promise.resolve(),\n preparePermissionChecks: true,\n };\n const provider = provideServices((scope) => openServices(scope, config, model, composed.flags));\n const composed = apiEntrypoints.customer(provider);\n const model = compileAccess(composed.access, {\n allowLookupResourcesOn: [tenantAccess.tenant],\n });\n const runtime = await composed.start();\n try {\n const { authorization, db, tenants, writeWithPermission } = runtime.read(provider);\n const notesPermission = tenantAccess.tenant.permissions.view;\n const owner = { type: account.wireName, id: randomUUID() };\n const subject = { type: account.wireName, id: randomUUID() };\n const tenant = await withSystemActor(\"test\", () => tenants.create(owner.id, \"Test\"));\n const resource = {\n type: notesPermission.entityWireName,\n id: tenant.id,\n };\n const memberRole = tenantAccess.tenant.roles.member.roleName;\n const membership = relationshipWrite(resource, memberRole, subject);\n const check = {\n subject,\n resource,\n permission: notesPermission.permissionName,\n };\n const removeMembership = {\n resourceType: resource.type,\n resourceId: resource.id,\n relation: memberRole,\n };\n await authorization.writeRelationships([membership]);\n\n const app = await createHttpApp({\n nodeEnv: \"test\",\n trustedOrigins: [baseUrl],\n logger: false,\n });\n try {\n registerRoutes(app, {\n routes: runtime.routes,\n accessModel: model,\n subjects: { resolve: () => Promise.resolve(subject) },\n authorization: {\n async check(query) {\n const allowed = await authorization.check(query);\n // Commit a revoke from outside the write while the HTTP gate's result is in flight.\n await authorization.deleteRelationships(removeMembership);\n return allowed;\n },\n },\n });\n expect(await authorization.check(check)).toBe(true);\n const refused = await app.inject({\n method: \"POST\",\n url: `/tenants/${tenant.id}/notes`,\n headers: { origin: baseUrl },\n payload: { text: \"Do not write\" },\n });\n expect(refused.statusCode).toBe(404);\n expect(await authorization.check(check)).toBe(false);\n expect((await db.execute(sql`SELECT id FROM starter_note`)).rows).toEqual([]);\n } finally {\n await app.close();\n }\n\n await authorization.writeRelationships([membership]);\n const forcedRollback = new Error(\"rollback both writes\");\n await expect(\n withSystemActor(\"test\", () =>\n writeWithPermission(\n { subject, resourceId: tenant.id, permission: notesPermission },\n async (tx, scopedAuthorization) => {\n await tx.execute(\n sql`INSERT INTO starter_note (id, tenant_id, text) VALUES (${
|
|
125
|
+
{ path: "tests/protected-write.integration.test.ts", content: "import { randomUUID } from \"node:crypto\";\n\nimport { compileAccess } from \"@dads-framework/access\";\nimport { relationshipWrite } from \"@dads-framework/access/runtime\";\nimport { withSystemActor } from \"@dads-framework/core/audit-actor\";\nimport { mintUuidV7 } from \"@dads-framework/core/contract\";\nimport { createHttpApp, registerRoutes } from \"@dads-framework/http\";\nimport { sql } from \"drizzle-orm\";\nimport { PostgreSqlContainer } from \"@testcontainers/postgresql\";\nimport { expect, it } from \"vitest\";\n\nimport { apiEntrypoints } from \"../assembly/api-entrypoints.js\";\nimport { migrate } from \"../assembly/migrations.js\";\nimport { openServices, provideServices } from \"../assembly/services.js\";\nimport { account, tenantAccess } from \"../libraries/app-runtime/index.js\";\n\nit(\"rechecks permission after the HTTP gate and rolls back data and access together\", { timeout: 90_000 }, async () => {\n const postgres = await new PostgreSqlContainer(\"postgres:16-alpine\").start();\n try {\n const databaseUrl = postgres.getConnectionUri();\n await migrate(databaseUrl);\n const baseUrl = \"http://127.0.0.1:3800\";\n const config = {\n databaseUrl,\n baseUrl,\n secret: \"fixture-signing-key-with-forty-characters\",\n enqueueEmail: () => Promise.resolve(),\n preparePermissionChecks: true,\n };\n const provider = provideServices((scope) => openServices(scope, config, model, composed.flags));\n const composed = apiEntrypoints.customer(provider);\n const model = compileAccess(composed.access, {\n allowLookupResourcesOn: [tenantAccess.tenant],\n });\n const runtime = await composed.start();\n try {\n const { authorization, db, tenants, writeWithPermission } = runtime.read(provider);\n const notesPermission = tenantAccess.tenant.permissions.view;\n const owner = { type: account.wireName, id: randomUUID() };\n const subject = { type: account.wireName, id: randomUUID() };\n const tenant = await withSystemActor(\"test\", () => tenants.create(owner.id, \"Test\"));\n const resource = {\n type: notesPermission.entityWireName,\n id: tenant.id,\n };\n const memberRole = tenantAccess.tenant.roles.member.roleName;\n const membership = relationshipWrite(resource, memberRole, subject);\n const check = {\n subject,\n resource,\n permission: notesPermission.permissionName,\n };\n const removeMembership = {\n resourceType: resource.type,\n resourceId: resource.id,\n relation: memberRole,\n };\n await authorization.writeRelationships([membership]);\n\n const app = await createHttpApp({\n nodeEnv: \"test\",\n trustedOrigins: [baseUrl],\n logger: false,\n });\n try {\n registerRoutes(app, {\n routes: runtime.routes,\n accessModel: model,\n subjects: { resolve: () => Promise.resolve(subject) },\n authorization: {\n async check(query) {\n const allowed = await authorization.check(query);\n // Commit a revoke from outside the write while the HTTP gate's result is in flight.\n await authorization.deleteRelationships(removeMembership);\n return allowed;\n },\n },\n });\n expect(await authorization.check(check)).toBe(true);\n const refused = await app.inject({\n method: \"POST\",\n url: `/tenants/${tenant.id}/notes`,\n headers: { origin: baseUrl },\n payload: { text: \"Do not write\" },\n });\n expect(refused.statusCode).toBe(404);\n expect(await authorization.check(check)).toBe(false);\n expect((await db.execute(sql`SELECT id FROM starter_note`)).rows).toEqual([]);\n } finally {\n await app.close();\n }\n\n await authorization.writeRelationships([membership]);\n const forcedRollback = new Error(\"rollback both writes\");\n await expect(\n withSystemActor(\"test\", () =>\n writeWithPermission(\n { subject, resourceId: tenant.id, permission: notesPermission },\n async (tx, scopedAuthorization) => {\n await tx.execute(\n sql`INSERT INTO starter_note (id, tenant_id, text) VALUES (${mintUuidV7()}, ${tenant.id}, 'Discard')`,\n );\n await scopedAuthorization.deleteRelationships(removeMembership);\n throw forcedRollback;\n },\n ),\n ),\n ).rejects.toBe(forcedRollback);\n expect((await db.execute(sql`SELECT id FROM starter_note`)).rows).toEqual([]);\n expect(await authorization.check(check)).toBe(true);\n\n const noteId = mintUuidV7();\n await withSystemActor(\"test\", () =>\n db.execute(sql`INSERT INTO starter_note (id, tenant_id, text) VALUES (${noteId}, ${tenant.id}, 'Before')`),\n );\n let attempts = 0;\n await expect(\n withSystemActor(\"test\", () =>\n writeWithPermission({ subject, resourceId: tenant.id, permission: notesPermission }, async (tx) => {\n attempts += 1;\n await db.execute(sql`UPDATE starter_note SET text = 'Other commit' WHERE id = ${noteId}`);\n await tx.execute(sql`UPDATE starter_note SET text = 'Stale write' WHERE id = ${noteId}`);\n }),\n ),\n ).rejects.toMatchObject({\n kind: \"conflict\",\n code: \"POSTGRES_CONFLICT\",\n details: { retryable: true },\n });\n expect(attempts).toBe(1);\n expect((await db.execute(sql`SELECT text FROM starter_note WHERE id = ${noteId}`)).rows).toEqual([\n { text: \"Other commit\" },\n ]);\n } finally {\n await runtime.stop();\n }\n } finally {\n await postgres.stop();\n }\n});\n" },
|
|
125
126
|
{ path: "tests/session-subjects.test.ts", content: "import type { IdentitySession } from \"@dads-framework/identity\";\nimport { expect, it, vi } from \"vitest\";\n\nimport { sessionSubjects } from \"../assembly/session-subjects.js\";\n\nit(\"requires the tenant's session policy on tenant routes\", async () => {\n const tenantId = \"c56a4180-65aa-4a42-80d3-f8e3159b9966\";\n const session: IdentitySession = {\n account: {\n id: \"user-1\",\n email: \"member@example.test\",\n emailVerified: true,\n },\n expiresAt: new Date(),\n };\n const readSession = vi.fn(() => Promise.resolve(session));\n const readTenantSession = vi.fn<(headers: Headers, tenantId: string) => Promise<null>>().mockResolvedValue(null);\n const identity = {\n handle: () => Promise.resolve(new Response(null)),\n readSession,\n readTenantSession,\n readEnterpriseSession: () => Promise.resolve(null),\n };\n const subjects = sessionSubjects(identity, identity);\n const headers = { cookie: \"fixture\" };\n expect(\n await subjects.resolve({\n headers,\n url: `/api/tenants/${tenantId.toUpperCase()}/notes?limit=1`,\n params: { tenantId: tenantId.toUpperCase() },\n }),\n ).toBeNull();\n expect(readTenantSession).toHaveBeenCalledWith(new Headers(headers), tenantId);\n expect(await subjects.resolve({ headers, params: { tenantId: \"invalid\" } })).toBeNull();\n expect(readTenantSession).toHaveBeenCalledTimes(1);\n expect(readSession).not.toHaveBeenCalled();\n expect(await subjects.resolve({ headers, url: \"/api/tenants\" })).toMatchObject({\n id: session.account.id,\n });\n});\n" },
|
|
126
127
|
{ path: "tests/sign-in-options-route.test.ts", content: "import { createHttpApp, registerRoutes } from \"@dads-framework/http\";\nimport { expect, it } from \"vitest\";\n\nimport { createSignInOptionsRoutes } from \"../assembly/sign-in-options-route.js\";\n\nit.each([true, false])(\"exposes only the SSO availability flag to signed-out users (%s)\", async (enabled) => {\n const http = await createHttpApp({\n nodeEnv: \"test\",\n trustedOrigins: [],\n logger: false,\n });\n try {\n registerRoutes(http, {\n routes: createSignInOptionsRoutes(enabled),\n subjects: { resolve: () => Promise.resolve(null) },\n authorization: { check: () => Promise.resolve(false) },\n });\n const result = await http.inject({\n method: \"GET\",\n url: \"/sign-in-options\",\n });\n expect(result.statusCode).toBe(200);\n expect(result.json()).toEqual({ data: { enterpriseSso: enabled } });\n } finally {\n await http.close();\n }\n});\n" },
|
|
127
128
|
{ path: "tests/staff-impersonation.integration.test.ts", content: "import { connectPostgresClient } from \"@dads-framework/postgres\";\nimport { PostgreSqlContainer } from \"@testcontainers/postgresql\";\nimport { tenantIdSchema } from \"@dads-framework/identity/tenants\";\nimport { expect, it } from \"vitest\";\nimport { z } from \"zod\";\n\nimport { migrate } from \"../assembly/migrations.js\";\nimport { startApp } from \"../assembly/start-app.js\";\nimport type { StarterEmail } from \"../libraries/app-runtime/index.js\";\n\nconst origin = \"http://127.0.0.1:3000\";\nconst password = \"starter-test-password-1\";\nconst endpoint = \"/api/staff/impersonation\";\ntype Http = Awaited<ReturnType<typeof startApp>>;\n\nit(\"restricts and audits staff support across real sessions and named APIs\", { timeout: 90_000 }, async () => {\n const postgres = await new PostgreSqlContainer(\"postgres:16-alpine\").start();\n const apps: Http[] = [];\n try {\n const databaseUrl = postgres.getConnectionUri();\n await migrate(databaseUrl);\n const emails: StarterEmail[] = [];\n const config = {\n databaseUrl,\n baseUrl: origin,\n secret: \"fixture-signing-key-with-forty-characters\",\n enqueueEmail: (message: StarterEmail) => {\n emails.push(message);\n return Promise.resolve();\n },\n };\n const disabled = await startApp(\"staff\", config);\n apps.push(disabled);\n const operator = await createAccount(disabled, emails, \"operator\");\n const target = await createAccount(disabled, emails, \"target\");\n const outsider = await createAccount(disabled, emails, \"outsider\");\n const created = await disabled.inject({\n method: \"POST\",\n url: \"/api/tenants\",\n headers: { origin, cookie: target.cookie },\n payload: { name: \"Customer tenant\" },\n });\n expect(created.statusCode).toBe(201);\n const tenant = z.object({ data: z.object({ id: tenantIdSchema }) }).parse(created.json()).data;\n const enterprise = {\n staffImpersonation: {\n tenantId: tenant.id,\n staffAccountIds: [operator.id],\n revokerAccountIds: [outsider.id],\n },\n };\n const customer = await startApp(\"customer\", { ...config, enterprise });\n apps.push(customer);\n const staff = await startApp(\"staff\", { ...config, enterprise });\n apps.push(staff);\n const start = { action: \"start\", effectiveAccountId: target.id };\n expect((await command(disabled, operator.cookie, start)).statusCode).toBe(404);\n expect((await command(customer, operator.cookie, start)).statusCode).toBe(404);\n expect((await command(staff, undefined, start)).statusCode).toBe(404);\n expect((await command(staff, target.cookie, start)).statusCode).toBe(404);\n expect(\n (\n await command(staff, operator.cookie, {\n ...start,\n effectiveAccountId: outsider.id,\n })\n ).statusCode,\n ).toBe(404);\n expect(\n (\n await command(staff, operator.cookie, {\n ...start,\n tenantId: tenant.id,\n })\n ).statusCode,\n ).toBe(400);\n\n const crossOrigin = await staff.inject({\n method: \"POST\",\n url: endpoint,\n headers: {\n origin: \"https://elsewhere.example\",\n cookie: operator.cookie,\n },\n payload: start,\n });\n expect(crossOrigin.statusCode).toBe(403);\n\n const first = await issue(staff, operator.cookie, start);\n const view = { action: \"view-tenant\", grantId: first };\n const otherSession = await signIn(staff, \"operator\", \"198.51.100.2\");\n expect((await command(staff, otherSession, view)).statusCode).toBe(404);\n const viewed = await command(staff, operator.cookie, view);\n expect(viewed.statusCode).toBe(200);\n expect(viewed.headers[\"cache-control\"]).toBe(\"no-store\");\n expect(viewed.json()).toEqual({\n staffAccountId: operator.id,\n effectiveAccountId: target.id,\n tenant: { id: tenant.id, name: \"Customer tenant\" },\n });\n\n const ordinaryAccess = await customer.inject({\n url: `/api/tenants/${tenant.id}/notes`,\n headers: { origin, cookie: operator.cookie },\n });\n expect(ordinaryAccess.statusCode).toBe(404);\n\n const stop = { action: \"stop\", grantId: first };\n expect((await command(staff, otherSession, stop)).statusCode).toBe(404);\n expect((await command(staff, operator.cookie, stop)).statusCode).toBe(200);\n expect((await command(staff, operator.cookie, view)).statusCode).toBe(404);\n\n const second = await issue(staff, operator.cookie, start);\n const revoke = { action: \"revoke\", grantId: second };\n expect((await command(staff, operator.cookie, revoke)).statusCode).toBe(404);\n expect((await command(staff, outsider.cookie, revoke)).statusCode).toBe(200);\n expect((await command(staff, operator.cookie, { ...view, grantId: second })).statusCode).toBe(404);\n\n expect(await readAuditEvents(databaseUrl)).toEqual(\n expect.arrayContaining([\n audit(\"start\", \"authorized\", first, operator.id),\n audit(\"use\", \"authorized\", first, operator.id),\n audit(\"use\", \"denied\", first, operator.id),\n audit(\"stop\", \"authorized\", first, operator.id),\n audit(\"revoke\", \"authorized\", second, outsider.id),\n ]),\n );\n function audit(action: string, outcome: string, grantId: string, actorAccountId: string) {\n const event: unknown = expect.objectContaining({\n action,\n outcome,\n grantId,\n actorAccountId,\n staffAccountId: operator.id,\n effectiveAccountId: target.id,\n tenantId: tenant.id,\n });\n return { event };\n }\n } finally {\n await Promise.all(apps.map((app) => app.close()));\n await postgres.stop();\n }\n});\n\nasync function createAccount(app: Http, emails: StarterEmail[], name: string) {\n const email = `${name}@example.test`;\n const created = await app.inject({\n method: \"POST\",\n url: \"/api/auth/sign-up/email\",\n headers: { origin },\n payload: { email, name, password },\n });\n expect(created.statusCode).toBe(200);\n const verify = emails.find((entry) => entry.to === email && entry.kind === \"verify-email\");\n if (verify === undefined) throw new Error(\"Missing verification email.\");\n const link = new URL(verify.url);\n const verified = await app.inject({\n url: link.pathname + link.search,\n headers: { origin },\n });\n expect([200, 302]).toContain(verified.statusCode);\n const cookie = await signIn(app, name);\n const session = await app.inject({\n url: \"/api/auth/get-session\",\n headers: { origin, cookie },\n });\n const { account } = z.object({ account: z.object({ id: z.string() }) }).parse(session.json());\n return { id: account.id, cookie };\n}\n\nasync function signIn(app: Http, name: string, ip = \"198.51.100.1\") {\n const signedIn = await app.inject({\n method: \"POST\",\n url: \"/api/auth/sign-in/email\",\n headers: { origin, \"x-forwarded-for\": ip },\n payload: { email: `${name}@example.test`, password },\n });\n expect(signedIn.statusCode).toBe(200);\n const raw = signedIn.headers[\"set-cookie\"];\n const cookies = Array.isArray(raw) ? raw : [raw];\n const cookie = cookies.flatMap((value) => value?.split(\";\")[0] ?? []).join(\"; \");\n expect(cookie).not.toBe(\"\");\n return cookie;\n}\n\nfunction command(app: Http, cookie: string | undefined, payload: object) {\n return app.inject({\n method: \"POST\",\n url: endpoint,\n headers: { origin, ...(cookie === undefined ? {} : { cookie }) },\n payload,\n });\n}\n\nasync function issue(app: Http, cookie: string, payload: object) {\n const response = await command(app, cookie, payload);\n expect(response.statusCode).toBe(201);\n expect(response.headers[\"set-cookie\"]).toBeUndefined();\n return z.object({ id: z.uuid() }).parse(response.json()).id;\n}\n\nasync function readAuditEvents(databaseUrl: string) {\n const client = await connectPostgresClient(databaseUrl);\n try {\n const result = await client.query<{ event: unknown }>(\"SELECT event FROM identity_staff_impersonation_audit\");\n return result.rows;\n } finally {\n await client.end();\n }\n}\n" },
|