@mdbase-dev/connect-dev 0.1.0-beta.100
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/LICENSE +21 -0
- package/README.md +86 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +30 -0
- package/dist/index.d.ts +107 -0
- package/dist/index.js +523 -0
- package/package.json +42 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 mdbase connect contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
# @mdbase-dev/connect-dev
|
|
2
|
+
|
|
3
|
+
Developer tools for applications built on mdbase connect.
|
|
4
|
+
|
|
5
|
+
The package provides canonical manifest and data-contract validation plus an
|
|
6
|
+
in-memory transport for frontend tests. The sandbox supports typed CRUD,
|
|
7
|
+
revision preconditions, read defaults, type-filtered pagination, and change
|
|
8
|
+
cursors. It rejects CEL filters and ordering so semantic tests cannot silently
|
|
9
|
+
depend on an approximation; run those against a real connector.
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { createSandbox } from "@mdbase-dev/connect-dev";
|
|
13
|
+
|
|
14
|
+
const { client } = createSandbox({
|
|
15
|
+
records: [{
|
|
16
|
+
path: "tasks/first.md",
|
|
17
|
+
types: ["task"],
|
|
18
|
+
frontmatter: { type: "task", title: "First" }
|
|
19
|
+
}]
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
const tasks = await client.query({ types: ["task"] });
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Validate artifacts from a project script:
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
mdbase-connect-dev validate-manifest public/.well-known/mdbase-app.json
|
|
29
|
+
mdbase-connect-dev validate-manifest public/.well-known/mdbase-app.json --allow-local
|
|
30
|
+
mdbase-connect-dev validate-contract worklog-contract.json
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Manifest validation uses the same canonical JSON Schema, semantic checks,
|
|
34
|
+
embedded-resource digest verification, and declaration-size bound as the
|
|
35
|
+
matching Connect server. Run it against the generated artifact in application
|
|
36
|
+
CI—not only against a handwritten source object. Failures include the exact
|
|
37
|
+
JSON-pointer path and rule.
|
|
38
|
+
|
|
39
|
+
Deployed applications can also submit `{ "manifest": ... }` to
|
|
40
|
+
`POST /v1/apps/validate`. That endpoint performs the same validation without
|
|
41
|
+
creating or updating an application registration, making it suitable for
|
|
42
|
+
release smoke tests.
|
|
43
|
+
|
|
44
|
+
Bundled application declarations support connector-controlled type-pack
|
|
45
|
+
provisioning. Put the contract, its implementing types, and any referenced
|
|
46
|
+
schemas in one `provisions.type_packs` transaction. Each manifest entry pins
|
|
47
|
+
the exact destination and SHA-256 digest. `provides` declares which exact
|
|
48
|
+
contracts the pack satisfies; auxiliary types belong in the same pack. The
|
|
49
|
+
validator rejects missing sources, digest mismatches, and claims for contracts
|
|
50
|
+
the application does not require.
|
|
51
|
+
|
|
52
|
+
Use `defineTypePack` to generate the manifest entries and digests from readable
|
|
53
|
+
documents:
|
|
54
|
+
|
|
55
|
+
```ts
|
|
56
|
+
import { defineTypePack } from "@mdbase-dev/connect-dev";
|
|
57
|
+
|
|
58
|
+
const provision = defineTypePack({
|
|
59
|
+
id: "example.tasks",
|
|
60
|
+
version: "1.0.0",
|
|
61
|
+
resources: [
|
|
62
|
+
{
|
|
63
|
+
kind: "contract",
|
|
64
|
+
mode: "managed",
|
|
65
|
+
source: "_contracts/example.task.md",
|
|
66
|
+
document: contractDocument
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
kind: "type",
|
|
70
|
+
mode: "seed",
|
|
71
|
+
source: "_types/task.md",
|
|
72
|
+
document: typeDocument
|
|
73
|
+
}
|
|
74
|
+
]
|
|
75
|
+
});
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
The helper validates each contract document and derives the exact semantic
|
|
79
|
+
`provides` descriptors. Managed resources evolve with the pack; seed resources
|
|
80
|
+
become collection-owned after their initial creation.
|
|
81
|
+
|
|
82
|
+
Native applications may add a reverse-domain private-use callback scheme that
|
|
83
|
+
matches the v1 manifest's application ID, such as
|
|
84
|
+
`example.tasks.desktop://auth/mdbase/callback` for
|
|
85
|
+
`id: "example.tasks.desktop"`. Native authorization still uses PKCE and should
|
|
86
|
+
open the authorization URL in the system browser.
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { resolve } from "node:path";
|
|
4
|
+
import { formatValidationIssues, validateAppManifest, validateDataContract } from "./index.js";
|
|
5
|
+
const arguments_ = process.argv.slice(2);
|
|
6
|
+
const allowLocal = arguments_.includes("--allow-local");
|
|
7
|
+
const [command, source] = arguments_.filter((argument) => argument !== "--allow-local");
|
|
8
|
+
if (!source || !["validate-manifest", "validate-contract"].includes(command ?? "")) {
|
|
9
|
+
console.error("Usage: mdbase-connect-dev <validate-manifest|validate-contract> <file.json> [--allow-local]");
|
|
10
|
+
process.exitCode = 2;
|
|
11
|
+
}
|
|
12
|
+
else {
|
|
13
|
+
try {
|
|
14
|
+
const value = JSON.parse(await readFile(resolve(source), "utf8"));
|
|
15
|
+
const result = command === "validate-manifest"
|
|
16
|
+
? validateAppManifest(value, { allowLocal })
|
|
17
|
+
: validateDataContract(value);
|
|
18
|
+
if (result.valid) {
|
|
19
|
+
console.log(`${source} is valid`);
|
|
20
|
+
}
|
|
21
|
+
else {
|
|
22
|
+
console.error(formatValidationIssues(result.issues));
|
|
23
|
+
process.exitCode = 1;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
28
|
+
process.exitCode = 1;
|
|
29
|
+
}
|
|
30
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { MdbaseCollectionClient, type MdbaseCollectionTransport } from "@mdbase-dev/connect/advanced";
|
|
2
|
+
import type { CollectionDescription, CollectionOperation, JsonObject, TypePackProvision } from "@mdbase-dev/connect-protocol";
|
|
3
|
+
import { formatManifestValidationIssues, validateAppManifest, type ManifestValidationIssue, type ManifestValidationOptions, type ManifestValidationResult } from "@mdbase-dev/connect-protocol/manifest";
|
|
4
|
+
export type ValidationIssue = ManifestValidationIssue;
|
|
5
|
+
export type ValidationResult = ManifestValidationResult;
|
|
6
|
+
export type { ManifestValidationOptions };
|
|
7
|
+
export { validateAppManifest };
|
|
8
|
+
export declare const formatValidationIssues: typeof formatManifestValidationIssues;
|
|
9
|
+
export declare function validateDataContract(value: unknown): ValidationResult;
|
|
10
|
+
export declare function validateProtocolValue(value: unknown, definition?: string): ValidationResult;
|
|
11
|
+
export interface DataContractDocument extends JsonObject {
|
|
12
|
+
kind: "mdbase.contract";
|
|
13
|
+
contract_type: "record" | "event" | "action";
|
|
14
|
+
id: string;
|
|
15
|
+
version: string;
|
|
16
|
+
}
|
|
17
|
+
export interface RecordDataContractDocument extends DataContractDocument {
|
|
18
|
+
contract_type: "record";
|
|
19
|
+
record_schema: JsonObject;
|
|
20
|
+
}
|
|
21
|
+
export interface EventDataContractDocument extends DataContractDocument {
|
|
22
|
+
contract_type: "event";
|
|
23
|
+
data_schema: JsonObject;
|
|
24
|
+
}
|
|
25
|
+
export interface ActionDataContractDocument extends DataContractDocument {
|
|
26
|
+
contract_type: "action";
|
|
27
|
+
input_schema: JsonObject;
|
|
28
|
+
}
|
|
29
|
+
export declare function defineDataContract<const Contract extends RecordDataContractDocument | EventDataContractDocument | ActionDataContractDocument>(contract: Contract): Contract;
|
|
30
|
+
export declare class DataContractDefinitionError extends Error {
|
|
31
|
+
readonly issues: ValidationIssue[];
|
|
32
|
+
constructor(issues: ValidationIssue[]);
|
|
33
|
+
}
|
|
34
|
+
export interface TypePackResourceInput {
|
|
35
|
+
kind: "contract" | "type" | "schema";
|
|
36
|
+
/** Managed resources evolve with the pack; seed resources become user-owned after creation. */
|
|
37
|
+
mode: "managed" | "seed";
|
|
38
|
+
source: string;
|
|
39
|
+
/** Collection-relative install location. Defaults to `source`. */
|
|
40
|
+
target?: string;
|
|
41
|
+
/** Exact UTF-8 resource document included in the provision. */
|
|
42
|
+
document: string;
|
|
43
|
+
}
|
|
44
|
+
export interface TypePackDefinition {
|
|
45
|
+
id: string;
|
|
46
|
+
version: string;
|
|
47
|
+
name?: string;
|
|
48
|
+
description?: string;
|
|
49
|
+
resources: TypePackResourceInput[];
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Build a complete, digest-pinned type-pack provision from readable source
|
|
53
|
+
* documents. This keeps application manifests reviewable without asking
|
|
54
|
+
* developers to calculate SHA-256 values by hand.
|
|
55
|
+
*/
|
|
56
|
+
export declare function defineTypePack(definition: TypePackDefinition): TypePackProvision;
|
|
57
|
+
/** Compute the portable semantic digest of one validated, fully resolved contract. */
|
|
58
|
+
export declare function dataContractDigest(contract: Record<string, unknown>): string;
|
|
59
|
+
export declare class DataContractDigestError extends Error {
|
|
60
|
+
}
|
|
61
|
+
export declare class TypePackDefinitionError extends Error {
|
|
62
|
+
readonly issues: ValidationIssue[];
|
|
63
|
+
constructor(issues: ValidationIssue[]);
|
|
64
|
+
}
|
|
65
|
+
export interface SandboxRecord<Frontmatter extends JsonObject = JsonObject> {
|
|
66
|
+
path: string;
|
|
67
|
+
frontmatter?: Frontmatter;
|
|
68
|
+
body?: string;
|
|
69
|
+
types?: string[];
|
|
70
|
+
}
|
|
71
|
+
export interface SandboxOptions<Frontmatter extends JsonObject = JsonObject> {
|
|
72
|
+
description?: Partial<CollectionDescription>;
|
|
73
|
+
records?: SandboxRecord<Frontmatter>[];
|
|
74
|
+
}
|
|
75
|
+
export interface DeveloperSandbox<Frontmatter extends JsonObject = JsonObject> {
|
|
76
|
+
client: MdbaseCollectionClient<Frontmatter>;
|
|
77
|
+
transport: SandboxTransport<Frontmatter>;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Build a deterministic, in-memory provider for frontend development.
|
|
81
|
+
*
|
|
82
|
+
* It intentionally implements the transport contract, CRUD preconditions,
|
|
83
|
+
* defaults, type filtering, pagination, and change cursors. It rejects query
|
|
84
|
+
* expression features so tests cannot silently rely on a non-conformant CEL
|
|
85
|
+
* approximation; use a real connector for semantic integration tests.
|
|
86
|
+
*/
|
|
87
|
+
export declare function createSandbox<Frontmatter extends JsonObject = JsonObject>(options?: SandboxOptions<Frontmatter>): DeveloperSandbox<Frontmatter>;
|
|
88
|
+
export declare class SandboxTransport<Frontmatter extends JsonObject = JsonObject> implements MdbaseCollectionTransport {
|
|
89
|
+
private readonly records;
|
|
90
|
+
private readonly events;
|
|
91
|
+
private revisionSequence;
|
|
92
|
+
readonly description: CollectionDescription;
|
|
93
|
+
constructor(options?: SandboxOptions<Frontmatter>);
|
|
94
|
+
seed(record: SandboxRecord<Frontmatter>): void;
|
|
95
|
+
snapshot(): SandboxRecord<Frontmatter>[];
|
|
96
|
+
operation<Result>(operation: CollectionOperation, input: unknown): Promise<Result>;
|
|
97
|
+
private changes;
|
|
98
|
+
private read;
|
|
99
|
+
private query;
|
|
100
|
+
private create;
|
|
101
|
+
private update;
|
|
102
|
+
private delete;
|
|
103
|
+
private rename;
|
|
104
|
+
private storedRecord;
|
|
105
|
+
private recordResult;
|
|
106
|
+
private append;
|
|
107
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,523 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { Ajv2020 } from "ajv/dist/2020.js";
|
|
3
|
+
import { parseDocument } from "yaml";
|
|
4
|
+
import { connectError, MdbaseCollectionClient } from "@mdbase-dev/connect/advanced";
|
|
5
|
+
import { formatManifestValidationIssues, validateAppManifest } from "@mdbase-dev/connect-protocol/manifest";
|
|
6
|
+
import connectProblemSchema from "@mdbase-dev/connect-protocol/schemas/connect-problem.v1.schema.json" with { type: "json" };
|
|
7
|
+
import dataContractSchema from "@mdbase-dev/connect-protocol/schemas/data-contract.schema.json" with { type: "json" };
|
|
8
|
+
import connectProtocolSchema from "@mdbase-dev/connect-protocol/schemas/connect-protocol.v1.schema.json" with { type: "json" };
|
|
9
|
+
import filesSchema from "@mdbase-dev/connect-protocol/schemas/files.v1.schema.json" with { type: "json" };
|
|
10
|
+
export { validateAppManifest };
|
|
11
|
+
export const formatValidationIssues = formatManifestValidationIssues;
|
|
12
|
+
const ajv = new Ajv2020({
|
|
13
|
+
allErrors: true,
|
|
14
|
+
strict: true,
|
|
15
|
+
// `required` may name properties declared by an enclosing allOf branch.
|
|
16
|
+
strictRequired: false,
|
|
17
|
+
formats: { "date-time": true, uri: true, uuid: true }
|
|
18
|
+
});
|
|
19
|
+
ajv.addSchema(connectProblemSchema);
|
|
20
|
+
ajv.addSchema(dataContractSchema);
|
|
21
|
+
ajv.addSchema(filesSchema);
|
|
22
|
+
ajv.addSchema(connectProtocolSchema);
|
|
23
|
+
const contractValidator = requiredValidator(String(dataContractSchema.$id));
|
|
24
|
+
export function validateDataContract(value) {
|
|
25
|
+
return validationResult(contractValidator, value);
|
|
26
|
+
}
|
|
27
|
+
export function validateProtocolValue(value, definition) {
|
|
28
|
+
const reference = definition
|
|
29
|
+
? `${String(connectProtocolSchema.$id)}#/$defs/${definition}`
|
|
30
|
+
: String(connectProtocolSchema.$id);
|
|
31
|
+
return validationResult(requiredValidator(reference), value);
|
|
32
|
+
}
|
|
33
|
+
export function defineDataContract(contract) {
|
|
34
|
+
const result = validateDataContract(contract);
|
|
35
|
+
if (!result.valid) {
|
|
36
|
+
throw new DataContractDefinitionError(result.issues);
|
|
37
|
+
}
|
|
38
|
+
return contract;
|
|
39
|
+
}
|
|
40
|
+
export class DataContractDefinitionError extends Error {
|
|
41
|
+
issues;
|
|
42
|
+
constructor(issues) {
|
|
43
|
+
super(`Invalid data contract: ${formatValidationIssues(issues)}`);
|
|
44
|
+
this.issues = issues;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Build a complete, digest-pinned type-pack provision from readable source
|
|
49
|
+
* documents. This keeps application manifests reviewable without asking
|
|
50
|
+
* developers to calculate SHA-256 values by hand.
|
|
51
|
+
*/
|
|
52
|
+
export function defineTypePack(definition) {
|
|
53
|
+
const provides = definition.resources
|
|
54
|
+
.map((resource, index) => ({ resource, index }))
|
|
55
|
+
.filter(({ resource }) => resource.kind === "contract")
|
|
56
|
+
.map(({ resource, index }) => {
|
|
57
|
+
if (resource.mode !== "managed") {
|
|
58
|
+
throw new TypePackDefinitionError([definitionIssue(`/resources/${index}/mode`, "contract_resource_mode", "contract resources must be managed so their declared version and digest can evolve with the pack")]);
|
|
59
|
+
}
|
|
60
|
+
return exactContractReferenceFromDocument(resource.document, index);
|
|
61
|
+
})
|
|
62
|
+
.sort((left, right) => left.id.localeCompare(right.id)
|
|
63
|
+
|| left.version.localeCompare(right.version)
|
|
64
|
+
|| left.digest.localeCompare(right.digest));
|
|
65
|
+
const provision = {
|
|
66
|
+
manifest: {
|
|
67
|
+
kind: "mdbase.type-pack",
|
|
68
|
+
id: definition.id,
|
|
69
|
+
version: definition.version,
|
|
70
|
+
...(definition.name ? { name: definition.name } : {}),
|
|
71
|
+
...(definition.description ? { description: definition.description } : {}),
|
|
72
|
+
resources: definition.resources.map(({ kind, mode, source, target = source, document }) => ({
|
|
73
|
+
kind,
|
|
74
|
+
mode,
|
|
75
|
+
source,
|
|
76
|
+
target,
|
|
77
|
+
digest: `sha256:${createHash("sha256").update(document).digest("hex")}`
|
|
78
|
+
}))
|
|
79
|
+
},
|
|
80
|
+
resources: definition.resources.map(({ source, document }) => ({ source, document })),
|
|
81
|
+
provides
|
|
82
|
+
};
|
|
83
|
+
const result = validateProtocolValue(provision, "typePackProvision");
|
|
84
|
+
if (!result.valid)
|
|
85
|
+
throw new TypePackDefinitionError(result.issues);
|
|
86
|
+
return provision;
|
|
87
|
+
}
|
|
88
|
+
function exactContractReferenceFromDocument(document, resourceIndex) {
|
|
89
|
+
const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u.exec(document)?.[1];
|
|
90
|
+
if (frontmatter === undefined) {
|
|
91
|
+
throw new TypePackDefinitionError([definitionIssue(`/resources/${resourceIndex}/document`, "contract_frontmatter", "contract resources must contain YAML frontmatter")]);
|
|
92
|
+
}
|
|
93
|
+
const parsed = parseDocument(frontmatter, { uniqueKeys: true });
|
|
94
|
+
if (parsed.errors.length > 0) {
|
|
95
|
+
throw new TypePackDefinitionError([definitionIssue(`/resources/${resourceIndex}/document`, "contract_frontmatter", `contract frontmatter is invalid: ${parsed.errors[0]?.message ?? "unknown YAML error"}`)]);
|
|
96
|
+
}
|
|
97
|
+
const contract = parsed.toJS({ maxAliasCount: 0 });
|
|
98
|
+
const validation = validateDataContract(contract);
|
|
99
|
+
if (!validation.valid)
|
|
100
|
+
throw new DataContractDefinitionError(validation.issues);
|
|
101
|
+
const value = contract;
|
|
102
|
+
return {
|
|
103
|
+
id: String(value.id),
|
|
104
|
+
version: String(value.version),
|
|
105
|
+
digest: dataContractDigest(value)
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
/** Compute the portable semantic digest of one validated, fully resolved contract. */
|
|
109
|
+
export function dataContractDigest(contract) {
|
|
110
|
+
const validation = validateDataContract(contract);
|
|
111
|
+
if (!validation.valid)
|
|
112
|
+
throw new DataContractDefinitionError(validation.issues);
|
|
113
|
+
const contractType = String(contract.contract_type);
|
|
114
|
+
const portable = {
|
|
115
|
+
kind: contract.kind,
|
|
116
|
+
contract_type: contract.contract_type,
|
|
117
|
+
id: contract.id,
|
|
118
|
+
version: contract.version
|
|
119
|
+
};
|
|
120
|
+
const schemaFields = contractType === "record"
|
|
121
|
+
? ["record_schema", "binding_schema"]
|
|
122
|
+
: contractType === "event"
|
|
123
|
+
? ["data_schema", "source_schema"]
|
|
124
|
+
: ["input_schema", "output_schema", "error_schema", "provider_schema"];
|
|
125
|
+
for (const field of schemaFields) {
|
|
126
|
+
const wrapper = contract[field];
|
|
127
|
+
if (wrapper === undefined)
|
|
128
|
+
continue;
|
|
129
|
+
if (!isRecord(wrapper) || !("value" in wrapper)) {
|
|
130
|
+
throw new DataContractDigestError(`${field} must be resolved to an inline JSON Schema before calculating a contract digest.`);
|
|
131
|
+
}
|
|
132
|
+
portable[field] = structuredClone(wrapper.value);
|
|
133
|
+
}
|
|
134
|
+
if (contractType === "action" && contract.behavior !== undefined) {
|
|
135
|
+
portable.behavior = structuredClone(contract.behavior);
|
|
136
|
+
}
|
|
137
|
+
return `sha256:${createHash("sha256").update(canonicalJson(portable)).digest("hex")}`;
|
|
138
|
+
}
|
|
139
|
+
export class DataContractDigestError extends Error {
|
|
140
|
+
}
|
|
141
|
+
export class TypePackDefinitionError extends Error {
|
|
142
|
+
issues;
|
|
143
|
+
constructor(issues) {
|
|
144
|
+
super(`Invalid type pack: ${formatValidationIssues(issues)}`);
|
|
145
|
+
this.issues = issues;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Build a deterministic, in-memory provider for frontend development.
|
|
150
|
+
*
|
|
151
|
+
* It intentionally implements the transport contract, CRUD preconditions,
|
|
152
|
+
* defaults, type filtering, pagination, and change cursors. It rejects query
|
|
153
|
+
* expression features so tests cannot silently rely on a non-conformant CEL
|
|
154
|
+
* approximation; use a real connector for semantic integration tests.
|
|
155
|
+
*/
|
|
156
|
+
export function createSandbox(options = {}) {
|
|
157
|
+
const transport = new SandboxTransport(options);
|
|
158
|
+
return { transport, client: new MdbaseCollectionClient(transport) };
|
|
159
|
+
}
|
|
160
|
+
export class SandboxTransport {
|
|
161
|
+
records = new Map();
|
|
162
|
+
events = [];
|
|
163
|
+
revisionSequence = 0;
|
|
164
|
+
description;
|
|
165
|
+
constructor(options = {}) {
|
|
166
|
+
this.description = sandboxDescription(options.description);
|
|
167
|
+
for (const record of options.records ?? [])
|
|
168
|
+
this.seed(record);
|
|
169
|
+
this.events.length = 0;
|
|
170
|
+
}
|
|
171
|
+
seed(record) {
|
|
172
|
+
assertSafePath(record.path);
|
|
173
|
+
this.records.set(record.path, this.storedRecord({
|
|
174
|
+
...record,
|
|
175
|
+
frontmatter: asObject(record.frontmatter)
|
|
176
|
+
}));
|
|
177
|
+
}
|
|
178
|
+
snapshot() {
|
|
179
|
+
return [...this.records.values()]
|
|
180
|
+
.sort((left, right) => left.path.localeCompare(right.path))
|
|
181
|
+
.map((record) => ({
|
|
182
|
+
path: record.path,
|
|
183
|
+
frontmatter: clone(record.frontmatter),
|
|
184
|
+
body: record.body,
|
|
185
|
+
types: [...record.types]
|
|
186
|
+
}));
|
|
187
|
+
}
|
|
188
|
+
async operation(operation, input) {
|
|
189
|
+
const object = asObject(input);
|
|
190
|
+
let result;
|
|
191
|
+
switch (operation) {
|
|
192
|
+
case "describe":
|
|
193
|
+
result = clone(this.description);
|
|
194
|
+
break;
|
|
195
|
+
case "changes":
|
|
196
|
+
result = this.changes(object);
|
|
197
|
+
break;
|
|
198
|
+
case "read":
|
|
199
|
+
result = this.read(object);
|
|
200
|
+
break;
|
|
201
|
+
case "query":
|
|
202
|
+
result = this.query(object);
|
|
203
|
+
break;
|
|
204
|
+
case "validate":
|
|
205
|
+
result = envelope({});
|
|
206
|
+
break;
|
|
207
|
+
case "create":
|
|
208
|
+
result = this.create(object);
|
|
209
|
+
break;
|
|
210
|
+
case "update":
|
|
211
|
+
result = this.update(object);
|
|
212
|
+
break;
|
|
213
|
+
case "delete":
|
|
214
|
+
result = this.delete(object);
|
|
215
|
+
break;
|
|
216
|
+
case "rename":
|
|
217
|
+
result = this.rename(object);
|
|
218
|
+
break;
|
|
219
|
+
default: throw connectError("unsupported_operation", `Unsupported sandbox operation: ${operation}`);
|
|
220
|
+
}
|
|
221
|
+
return clone(result);
|
|
222
|
+
}
|
|
223
|
+
changes(input) {
|
|
224
|
+
const current = this.events.length;
|
|
225
|
+
if (input.after === undefined) {
|
|
226
|
+
return { events: [], cursor: current, has_more: false, reset: false };
|
|
227
|
+
}
|
|
228
|
+
const after = integer(input.after, "after", 0);
|
|
229
|
+
const limit = integer(input.limit ?? 200, "limit", 1);
|
|
230
|
+
const available = this.events.filter((event) => event.cursor > after);
|
|
231
|
+
const events = available.slice(0, limit);
|
|
232
|
+
return {
|
|
233
|
+
events,
|
|
234
|
+
cursor: events.at(-1)?.cursor ?? after,
|
|
235
|
+
has_more: available.length > events.length,
|
|
236
|
+
reset: false
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
read(input) {
|
|
240
|
+
const path = string(input.path, "path");
|
|
241
|
+
const record = this.records.get(path);
|
|
242
|
+
if (!record)
|
|
243
|
+
return invalid("file_not_found", `File not found: ${path}`, path);
|
|
244
|
+
return envelope(this.recordResult(record));
|
|
245
|
+
}
|
|
246
|
+
query(input) {
|
|
247
|
+
if (input.where !== undefined || input.order_by !== undefined) {
|
|
248
|
+
throw connectError("sandbox_unsupported", "The in-memory sandbox does not emulate CEL or ordering. Run this test against a real connector.");
|
|
249
|
+
}
|
|
250
|
+
const types = Array.isArray(input.types)
|
|
251
|
+
? input.types.filter((value) => typeof value === "string")
|
|
252
|
+
: [];
|
|
253
|
+
const all = [...this.records.values()]
|
|
254
|
+
.filter((record) => types.length === 0 || record.types.some((type) => types.includes(type)))
|
|
255
|
+
.sort((left, right) => left.path.localeCompare(right.path));
|
|
256
|
+
const offset = integer(input.offset ?? 0, "offset", 0);
|
|
257
|
+
const limit = integer(input.limit ?? all.length, "limit", 0);
|
|
258
|
+
const selected = all.slice(offset, offset + limit).map((record) => {
|
|
259
|
+
const document = this.recordResult(record);
|
|
260
|
+
const result = {
|
|
261
|
+
path: document.path,
|
|
262
|
+
types: document.types,
|
|
263
|
+
file: { ...document.file, path: document.path }
|
|
264
|
+
};
|
|
265
|
+
const mode = input.frontmatter_mode ?? "effective";
|
|
266
|
+
if (mode === "persisted" || mode === "both") {
|
|
267
|
+
result.frontmatter = document.frontmatter;
|
|
268
|
+
}
|
|
269
|
+
if (mode === "effective" || mode === "both") {
|
|
270
|
+
result.effective_frontmatter = document.effective_frontmatter;
|
|
271
|
+
}
|
|
272
|
+
if (input.include_body !== true)
|
|
273
|
+
delete result.body;
|
|
274
|
+
else
|
|
275
|
+
result.body = document.body;
|
|
276
|
+
return result;
|
|
277
|
+
});
|
|
278
|
+
return envelope({
|
|
279
|
+
results: selected,
|
|
280
|
+
meta: {
|
|
281
|
+
total_count: all.length,
|
|
282
|
+
has_more: offset + selected.length < all.length
|
|
283
|
+
}
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
create(input) {
|
|
287
|
+
const path = string(input.path, "path");
|
|
288
|
+
assertSafePath(path);
|
|
289
|
+
if (this.records.has(path))
|
|
290
|
+
return invalid("path_conflict", `File already exists: ${path}`, path);
|
|
291
|
+
if (input.if_revision !== undefined) {
|
|
292
|
+
return invalid("concurrent_modification", `File does not match the requested revision: ${path}`, path);
|
|
293
|
+
}
|
|
294
|
+
const frontmatter = asObject(input.frontmatter);
|
|
295
|
+
const type = typeof input.type === "string" ? input.type.toLowerCase() : undefined;
|
|
296
|
+
const record = this.storedRecord({
|
|
297
|
+
path,
|
|
298
|
+
frontmatter,
|
|
299
|
+
body: typeof input.body === "string" ? input.body : "",
|
|
300
|
+
types: type ? [type] : explicitTypes(frontmatter)
|
|
301
|
+
});
|
|
302
|
+
this.records.set(path, record);
|
|
303
|
+
this.append("mdbase.record.created", record, { path, types: record.types });
|
|
304
|
+
return envelope(this.recordResult(record));
|
|
305
|
+
}
|
|
306
|
+
update(input) {
|
|
307
|
+
const path = string(input.path, "path");
|
|
308
|
+
const current = this.records.get(path);
|
|
309
|
+
if (!current)
|
|
310
|
+
return invalid("file_not_found", `File not found: ${path}`, path);
|
|
311
|
+
const revisionError = checkRevision(input, current);
|
|
312
|
+
if (revisionError)
|
|
313
|
+
return revisionError;
|
|
314
|
+
const patch = asObject(input.patch ?? {});
|
|
315
|
+
const frontmatter = clone(current.frontmatter);
|
|
316
|
+
for (const [field, value] of Object.entries(patch))
|
|
317
|
+
frontmatter[field] = clone(value);
|
|
318
|
+
const record = this.storedRecord({
|
|
319
|
+
path,
|
|
320
|
+
frontmatter: frontmatter,
|
|
321
|
+
body: typeof input.body === "string" ? input.body : current.body,
|
|
322
|
+
types: explicitTypes(frontmatter).length > 0 ? explicitTypes(frontmatter) : current.types
|
|
323
|
+
});
|
|
324
|
+
this.records.set(path, record);
|
|
325
|
+
this.append("mdbase.record.modified", record, { path, types: record.types, changed_fields: Object.keys(patch) });
|
|
326
|
+
return envelope(this.recordResult(record));
|
|
327
|
+
}
|
|
328
|
+
delete(input) {
|
|
329
|
+
const path = string(input.path, "path");
|
|
330
|
+
const current = this.records.get(path);
|
|
331
|
+
if (!current)
|
|
332
|
+
return invalid("file_not_found", `File not found: ${path}`, path);
|
|
333
|
+
const revisionError = checkRevision(input, current);
|
|
334
|
+
if (revisionError)
|
|
335
|
+
return revisionError;
|
|
336
|
+
if (input.dry_run === true) {
|
|
337
|
+
return envelope({
|
|
338
|
+
path,
|
|
339
|
+
deleted: false,
|
|
340
|
+
dry_run: true,
|
|
341
|
+
would_delete: true
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
this.records.delete(path);
|
|
345
|
+
this.append("mdbase.record.deleted", current, { path, types: current.types });
|
|
346
|
+
return envelope({ path, deleted: true });
|
|
347
|
+
}
|
|
348
|
+
rename(input) {
|
|
349
|
+
const from = string(input.from, "from");
|
|
350
|
+
const to = string(input.to, "to");
|
|
351
|
+
assertSafePath(to);
|
|
352
|
+
const current = this.records.get(from);
|
|
353
|
+
if (!current)
|
|
354
|
+
return invalid("file_not_found", `File not found: ${from}`, from);
|
|
355
|
+
const revisionError = checkRevision(input, current);
|
|
356
|
+
if (revisionError)
|
|
357
|
+
return revisionError;
|
|
358
|
+
if (this.records.has(to))
|
|
359
|
+
return invalid("path_conflict", `File already exists: ${to}`, to);
|
|
360
|
+
if (input.dry_run === true) {
|
|
361
|
+
return envelope({
|
|
362
|
+
from,
|
|
363
|
+
to,
|
|
364
|
+
dry_run: true,
|
|
365
|
+
would_rename: true
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
this.records.delete(from);
|
|
369
|
+
const record = this.storedRecord({ ...current, path: to });
|
|
370
|
+
this.records.set(to, record);
|
|
371
|
+
this.append("mdbase.record.renamed", record, { from, to, types: record.types });
|
|
372
|
+
return envelope({ ...this.recordResult(record), from, to, references_updated: [] });
|
|
373
|
+
}
|
|
374
|
+
storedRecord(record) {
|
|
375
|
+
return {
|
|
376
|
+
path: record.path,
|
|
377
|
+
frontmatter: clone(record.frontmatter),
|
|
378
|
+
body: record.body ?? "",
|
|
379
|
+
types: [...(record.types ?? explicitTypes(record.frontmatter))],
|
|
380
|
+
revision: `sandbox:${++this.revisionSequence}`
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
recordResult(record) {
|
|
384
|
+
const effective = clone(record.frontmatter);
|
|
385
|
+
for (const typeName of record.types) {
|
|
386
|
+
const type = this.description.types.find((candidate) => candidate.name === typeName);
|
|
387
|
+
const defaults = asObject(type?.collection?.read_defaults);
|
|
388
|
+
for (const [field, value] of Object.entries(defaults)) {
|
|
389
|
+
if (!(field in effective))
|
|
390
|
+
effective[field] = clone(value);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
return {
|
|
394
|
+
path: record.path,
|
|
395
|
+
frontmatter: clone(record.frontmatter),
|
|
396
|
+
effective_frontmatter: effective,
|
|
397
|
+
body: record.body,
|
|
398
|
+
types: [...record.types],
|
|
399
|
+
revision: record.revision,
|
|
400
|
+
file: sandboxFileMetadata(record)
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
append(type, record, payload) {
|
|
404
|
+
const cursor = this.events.length + 1;
|
|
405
|
+
this.events.push({
|
|
406
|
+
cursor,
|
|
407
|
+
type,
|
|
408
|
+
occurred_at: new Date(cursor).toISOString(),
|
|
409
|
+
payload: { ...clone(payload), revision: record.revision }
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
function sandboxFileMetadata(record) {
|
|
414
|
+
const segments = record.path.split("/");
|
|
415
|
+
const name = segments.at(-1) ?? record.path;
|
|
416
|
+
const folder = segments.slice(0, -1).join("/");
|
|
417
|
+
const revision = Number(record.revision.split(":").at(-1) ?? 0);
|
|
418
|
+
const serialized = `---\n${JSON.stringify(record.frontmatter)}\n---\n${record.body}`;
|
|
419
|
+
return {
|
|
420
|
+
name,
|
|
421
|
+
folder,
|
|
422
|
+
size: new TextEncoder().encode(serialized).byteLength,
|
|
423
|
+
mtime: new Date(revision).toISOString()
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
function requiredValidator(reference) {
|
|
427
|
+
const validate = ajv.getSchema(reference);
|
|
428
|
+
if (!validate)
|
|
429
|
+
throw new Error(`Canonical schema is unavailable: ${reference}`);
|
|
430
|
+
return validate;
|
|
431
|
+
}
|
|
432
|
+
function validationResult(validate, value) {
|
|
433
|
+
if (validate(value))
|
|
434
|
+
return { valid: true, issues: [] };
|
|
435
|
+
return {
|
|
436
|
+
valid: false,
|
|
437
|
+
issues: (validate.errors ?? []).map(validationIssue)
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
function validationIssue(error) {
|
|
441
|
+
return {
|
|
442
|
+
path: error.instancePath,
|
|
443
|
+
keyword: error.keyword,
|
|
444
|
+
message: error.message ?? "is invalid",
|
|
445
|
+
params: error.params
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
function definitionIssue(path, keyword, message) {
|
|
449
|
+
return { path, keyword, message, params: {} };
|
|
450
|
+
}
|
|
451
|
+
function isRecord(value) {
|
|
452
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
453
|
+
}
|
|
454
|
+
function canonicalJson(value) {
|
|
455
|
+
if (value === null || typeof value !== "object")
|
|
456
|
+
return JSON.stringify(value);
|
|
457
|
+
if (Array.isArray(value))
|
|
458
|
+
return `[${value.map(canonicalJson).join(",")}]`;
|
|
459
|
+
return `{${Object.entries(value)
|
|
460
|
+
.filter(([, child]) => child !== undefined)
|
|
461
|
+
.sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0)
|
|
462
|
+
.map(([key, child]) => `${JSON.stringify(key)}:${canonicalJson(child)}`)
|
|
463
|
+
.join(",")}}`;
|
|
464
|
+
}
|
|
465
|
+
function sandboxDescription(value = {}) {
|
|
466
|
+
return {
|
|
467
|
+
protocol_version: 1,
|
|
468
|
+
collection_id: value.collection_id ?? "01900000-0000-7000-8000-000000000001",
|
|
469
|
+
display_name: value.display_name ?? "Developer sandbox",
|
|
470
|
+
spec_version: value.spec_version ?? "0.3.0",
|
|
471
|
+
operations: value.operations ?? ["describe", "changes", "read", "query", "list_views", "execute_view", "read_view_source", "validate", "create", "update", "delete", "rename", "create_view_source", "update_view_source", "delete_view_source", "read_type", "create_type", "update_type", "assess_type_pack", "apply_type_pack"],
|
|
472
|
+
change_cursor: value.change_cursor ?? 0,
|
|
473
|
+
types: clone(value.types ?? []),
|
|
474
|
+
contracts: clone(value.contracts ?? [])
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
function envelope(result) {
|
|
478
|
+
return { valid: true, result: result, diagnostics: [] };
|
|
479
|
+
}
|
|
480
|
+
function invalid(code, message, path) {
|
|
481
|
+
return {
|
|
482
|
+
valid: false,
|
|
483
|
+
result: {},
|
|
484
|
+
diagnostics: [{ severity: "error", code, message, path }]
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
function checkRevision(input, record) {
|
|
488
|
+
if (input.if_revision === undefined || input.if_revision === record.revision)
|
|
489
|
+
return null;
|
|
490
|
+
return invalid("concurrent_modification", `File does not match the requested revision: ${record.path}`, record.path);
|
|
491
|
+
}
|
|
492
|
+
function explicitTypes(frontmatter) {
|
|
493
|
+
const values = [frontmatter.type, frontmatter.types]
|
|
494
|
+
.flatMap((value) => Array.isArray(value) ? value : [value])
|
|
495
|
+
.filter((value) => typeof value === "string" && value.length > 0)
|
|
496
|
+
.map((value) => value.toLowerCase());
|
|
497
|
+
return [...new Set(values)];
|
|
498
|
+
}
|
|
499
|
+
function assertSafePath(path) {
|
|
500
|
+
if (!path || path.startsWith("/") || path.includes("\\") || path.split("/").includes("..")) {
|
|
501
|
+
throw connectError("invalid_path", `Unsafe sandbox path: ${path}`);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
function asObject(value) {
|
|
505
|
+
return value !== null && typeof value === "object" && !Array.isArray(value)
|
|
506
|
+
? value
|
|
507
|
+
: {};
|
|
508
|
+
}
|
|
509
|
+
function string(value, field) {
|
|
510
|
+
if (typeof value !== "string" || value.length === 0) {
|
|
511
|
+
throw connectError("invalid_request", `${field} must be a non-empty string.`);
|
|
512
|
+
}
|
|
513
|
+
return value;
|
|
514
|
+
}
|
|
515
|
+
function integer(value, field, minimum) {
|
|
516
|
+
if (!Number.isInteger(value) || Number(value) < minimum) {
|
|
517
|
+
throw connectError("invalid_request", `${field} must be an integer of at least ${minimum}.`);
|
|
518
|
+
}
|
|
519
|
+
return Number(value);
|
|
520
|
+
}
|
|
521
|
+
function clone(value) {
|
|
522
|
+
return structuredClone(value);
|
|
523
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@mdbase-dev/connect-dev",
|
|
3
|
+
"version": "0.1.0-beta.100",
|
|
4
|
+
"private": false,
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/mdbase-dev/mdbase-connect.git",
|
|
10
|
+
"directory": "packages/devkit"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://mdbase.dev",
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"import": "./dist/index.js"
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"bin": {
|
|
20
|
+
"mdbase-connect-dev": "./dist/cli.js"
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"dist",
|
|
24
|
+
"README.md"
|
|
25
|
+
],
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"ajv": "^8.20.0",
|
|
28
|
+
"yaml": "^2.9.0",
|
|
29
|
+
"@mdbase-dev/connect": "0.1.0-beta.100",
|
|
30
|
+
"@mdbase-dev/connect-protocol": "0.1.0-beta.100"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"@types/node": "^24.0.0",
|
|
34
|
+
"typescript": "^7.0.2",
|
|
35
|
+
"vitest": "^4.1.10"
|
|
36
|
+
},
|
|
37
|
+
"scripts": {
|
|
38
|
+
"build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.json && node -e \"require('node:fs').chmodSync('dist/cli.js',0o755)\"",
|
|
39
|
+
"test": "vitest run",
|
|
40
|
+
"typecheck": "tsc -p tsconfig.json --noEmit"
|
|
41
|
+
}
|
|
42
|
+
}
|