@open-mercato/cli 0.11.1-develop.8593.1.50784dae35 → 0.11.1-develop.8665.1.2455b2503c
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/.turbo/turbo-build.log +4 -2
- package/AGENTS.md +2 -0
- package/dist/agentic/guides/architecture.md +2 -2
- package/dist/agentic/guides/extensions.md +7 -2
- package/dist/agentic/guides/framework-extension-points.md +1 -0
- package/dist/agentic/guides/infrastructure-providers.md +20 -0
- package/dist/agentic/guides/integrations.md +2 -2
- package/dist/agentic/guides/module-facts.json +2564 -265
- package/dist/agentic/guides/module-facts.v2.json +2580 -265
- package/dist/agentic/guides/modules/agent_orchestrator/index.md +1 -1
- package/dist/agentic/guides/modules/ai_assistant/index.md +1 -1
- package/dist/agentic/guides/modules/api_docs/index.md +1 -1
- package/dist/agentic/guides/modules/api_keys/index.md +1 -1
- package/dist/agentic/guides/modules/assisted_selling/acl-features.md +16 -0
- package/dist/agentic/guides/modules/assisted_selling/contribution-resolutions.md +21 -0
- package/dist/agentic/guides/modules/assisted_selling/domain-commands.md +11 -0
- package/dist/agentic/guides/modules/assisted_selling/entities.md +11 -0
- package/dist/agentic/guides/modules/assisted_selling/events.md +22 -0
- package/dist/agentic/guides/modules/assisted_selling/exact-override-targets.md +17 -0
- package/dist/agentic/guides/modules/assisted_selling/index.md +21 -0
- package/dist/agentic/guides/modules/assisted_selling/owned-contract-module-metadata.md +11 -0
- package/dist/agentic/guides/modules/assisted_selling/setup.md +11 -0
- package/dist/agentic/guides/modules/assisted_selling/umes-contributions.md +21 -0
- package/dist/agentic/guides/modules/assisted_selling/umes-hosts.md +23 -0
- package/dist/agentic/guides/modules/attachments/exact-override-targets.md +1 -1
- package/dist/agentic/guides/modules/attachments/index.md +1 -1
- package/dist/agentic/guides/modules/attachments/workers.md +1 -1
- package/dist/agentic/guides/modules/audit_logs/index.md +1 -1
- package/dist/agentic/guides/modules/auth/index.md +1 -1
- package/dist/agentic/guides/modules/availability/index.md +1 -1
- package/dist/agentic/guides/modules/backups/di-registrations-rich.md +11 -0
- package/dist/agentic/guides/modules/backups/di-service-tokens.md +11 -0
- package/dist/agentic/guides/modules/backups/exact-override-targets.md +11 -0
- package/dist/agentic/guides/modules/backups/index.md +5 -2
- package/dist/agentic/guides/modules/business_rules/index.md +1 -1
- package/dist/agentic/guides/modules/carrier_inpost/index.md +1 -1
- package/dist/agentic/guides/modules/cart/index.md +1 -1
- package/dist/agentic/guides/modules/catalog/acl-features.md +2 -1
- package/dist/agentic/guides/modules/catalog/active-extension-bindings.md +2 -0
- package/dist/agentic/guides/modules/catalog/backend-pages.md +1 -0
- package/dist/agentic/guides/modules/catalog/contribution-resolutions.md +5 -0
- package/dist/agentic/guides/modules/catalog/di-registrations-rich.md +8 -7
- package/dist/agentic/guides/modules/catalog/di-service-tokens.md +5 -4
- package/dist/agentic/guides/modules/catalog/domain-commands.md +2 -0
- package/dist/agentic/guides/modules/catalog/entities.md +1 -0
- package/dist/agentic/guides/modules/catalog/events.md +4 -1
- package/dist/agentic/guides/modules/catalog/exact-override-targets.md +13 -7
- package/dist/agentic/guides/modules/catalog/index.md +9 -9
- package/dist/agentic/guides/modules/catalog/umes-contributions.md +5 -0
- package/dist/agentic/guides/modules/catalog/umes-hosts.md +4 -0
- package/dist/agentic/guides/modules/catalog/workers.md +1 -0
- package/dist/agentic/guides/modules/channel_apns/index.md +1 -1
- package/dist/agentic/guides/modules/channel_discord/index.md +1 -1
- package/dist/agentic/guides/modules/channel_expo/index.md +1 -1
- package/dist/agentic/guides/modules/channel_fcm/index.md +1 -1
- package/dist/agentic/guides/modules/channel_gmail/index.md +1 -1
- package/dist/agentic/guides/modules/channel_imap/index.md +1 -1
- package/dist/agentic/guides/modules/channel_resend/index.md +1 -1
- package/dist/agentic/guides/modules/channel_ses/index.md +1 -1
- package/dist/agentic/guides/modules/channel_smtp/index.md +1 -1
- package/dist/agentic/guides/modules/checkout/index.md +1 -1
- package/dist/agentic/guides/modules/communication_channels/index.md +1 -1
- package/dist/agentic/guides/modules/configs/index.md +1 -1
- package/dist/agentic/guides/modules/content/index.md +1 -1
- package/dist/agentic/guides/modules/currencies/index.md +1 -1
- package/dist/agentic/guides/modules/customer_accounts/active-extension-bindings.md +1 -1
- package/dist/agentic/guides/modules/customer_accounts/exact-override-targets.md +2 -0
- package/dist/agentic/guides/modules/customer_accounts/index.md +2 -2
- package/dist/agentic/guides/modules/customer_accounts/workers.md +2 -0
- package/dist/agentic/guides/modules/customer_groups/index.md +1 -1
- package/dist/agentic/guides/modules/customers/active-extension-bindings.md +2 -1
- package/dist/agentic/guides/modules/customers/incoming-installed-contributions.md +1 -0
- package/dist/agentic/guides/modules/customers/index.md +3 -3
- package/dist/agentic/guides/modules/customers/umes-hosts.md +1 -0
- package/dist/agentic/guides/modules/dashboards/active-extension-bindings.md +0 -1
- package/dist/agentic/guides/modules/dashboards/cli-commands.md +1 -0
- package/dist/agentic/guides/modules/dashboards/exact-override-targets.md +1 -0
- package/dist/agentic/guides/modules/dashboards/index.md +2 -3
- package/dist/agentic/guides/modules/data_sync/index.md +1 -1
- package/dist/agentic/guides/modules/design_system/index.md +1 -1
- package/dist/agentic/guides/modules/devices/index.md +1 -1
- package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
- package/dist/agentic/guides/modules/directory/index.md +1 -1
- package/dist/agentic/guides/modules/documents/index.md +1 -1
- package/dist/agentic/guides/modules/ecommerce/index.md +1 -1
- package/dist/agentic/guides/modules/entities/index.md +1 -1
- package/dist/agentic/guides/modules/eudr/index.md +1 -1
- package/dist/agentic/guides/modules/events/index.md +1 -1
- package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
- package/dist/agentic/guides/modules/forms/index.md +1 -1
- package/dist/agentic/guides/modules/gateway_autopay/index.md +1 -1
- package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
- package/dist/agentic/guides/modules/gateway_tpay/index.md +1 -1
- package/dist/agentic/guides/modules/generators/index.md +1 -1
- package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
- package/dist/agentic/guides/modules/integrations/di-registrations-rich.md +8 -8
- package/dist/agentic/guides/modules/integrations/di-service-tokens.md +4 -4
- package/dist/agentic/guides/modules/integrations/exact-override-targets.md +14 -12
- package/dist/agentic/guides/modules/integrations/index.md +2 -2
- package/dist/agentic/guides/modules/integrations/setup.md +1 -1
- package/dist/agentic/guides/modules/integrations/workers.md +3 -1
- package/dist/agentic/guides/modules/messages/index.md +1 -1
- package/dist/agentic/guides/modules/notifications/index.md +1 -1
- package/dist/agentic/guides/modules/onboarding/index.md +1 -1
- package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
- package/dist/agentic/guides/modules/perspectives/index.md +1 -1
- package/dist/agentic/guides/modules/phone_calls/index.md +1 -1
- package/dist/agentic/guides/modules/planner/index.md +1 -1
- package/dist/agentic/guides/modules/portal/index.md +1 -1
- package/dist/agentic/guides/modules/progress/index.md +1 -1
- package/dist/agentic/guides/modules/promotions/index.md +1 -1
- package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
- package/dist/agentic/guides/modules/query_index/index.md +1 -1
- package/dist/agentic/guides/modules/record_locks/index.md +1 -1
- package/dist/agentic/guides/modules/resources/exact-override-targets.md +3 -3
- package/dist/agentic/guides/modules/resources/index.md +1 -1
- package/dist/agentic/guides/modules/resources/owned-contract-module-metadata.md +1 -1
- package/dist/agentic/guides/modules/resources/setup.md +1 -1
- package/dist/agentic/guides/modules/sales/contribution-resolutions.md +1 -0
- package/dist/agentic/guides/modules/sales/exact-override-targets.md +1 -0
- package/dist/agentic/guides/modules/sales/index.md +3 -3
- package/dist/agentic/guides/modules/sales/umes-contributions.md +1 -0
- package/dist/agentic/guides/modules/scheduler/index.md +1 -1
- package/dist/agentic/guides/modules/search/index.md +1 -1
- package/dist/agentic/guides/modules/security/index.md +1 -1
- package/dist/agentic/guides/modules/seeds/index.md +1 -1
- package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
- package/dist/agentic/guides/modules/sso/index.md +1 -1
- package/dist/agentic/guides/modules/staff/contribution-resolutions.md +1 -1
- package/dist/agentic/guides/modules/staff/exact-override-targets.md +1 -1
- package/dist/agentic/guides/modules/staff/index.md +1 -1
- package/dist/agentic/guides/modules/staff/workers.md +1 -1
- package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
- package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
- package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
- package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
- package/dist/agentic/guides/modules/telemetry/index.md +1 -1
- package/dist/agentic/guides/modules/tillio/index.md +1 -1
- package/dist/agentic/guides/modules/translations/index.md +1 -1
- package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
- package/dist/agentic/guides/modules/webhooks/index.md +1 -1
- package/dist/agentic/guides/modules/wms/index.md +1 -1
- package/dist/agentic/guides/modules/workflows/index.md +1 -1
- package/dist/agentic/guides/reference-module-facts.json +811 -21
- package/dist/agentic/guides/reference-modules/example/active-extension-bindings.md +1 -0
- package/dist/agentic/guides/reference-modules/example/backend-pages.md +2 -0
- package/dist/agentic/guides/reference-modules/example/contribution-resolutions.md +3 -1
- package/dist/agentic/guides/reference-modules/example/di-registrations-rich.md +3 -3
- package/dist/agentic/guides/reference-modules/example/di-service-tokens.md +1 -1
- package/dist/agentic/guides/reference-modules/example/entities.md +2 -0
- package/dist/agentic/guides/reference-modules/example/events.md +2 -1
- package/dist/agentic/guides/reference-modules/example/exact-override-targets.md +25 -8
- package/dist/agentic/guides/reference-modules/example/index.md +7 -7
- package/dist/agentic/guides/reference-modules/example/notifications.md +1 -0
- package/dist/agentic/guides/reference-modules/example/setup.md +1 -1
- package/dist/agentic/guides/reference-modules/example/umes-contributions.md +3 -1
- package/dist/agentic/guides/reference-modules/example/umes-hosts.md +4 -0
- package/dist/agentic/guides/upstream/AGENTS.md +5 -4
- package/dist/agentic/guides/upstream/BACKWARD_COMPATIBILITY.md +37 -20
- package/dist/agentic/guides/upstream/manifest.json +3 -3
- package/dist/agentic/shared/AGENTS.md.template +11 -15
- package/dist/agentic/shared/ai/harness/README.md +4 -2
- package/dist/agentic/shared/ai/harness/RELEASE.md +4 -4
- package/dist/agentic/shared/ai/harness/cases.json +1420 -41
- package/dist/agentic/shared/ai/harness/cases.schema.json +4 -4
- package/dist/agentic/shared/ai/harness/design-system-inventory.json +640 -142
- package/dist/agentic/shared/ai/harness/source-link-inventory.json +223 -16
- package/dist/agentic/shared/ai/harness/validators.json +1 -1
- package/dist/agentic/shared/ai/skills/om-system-extension/SKILL.md +1 -1
- package/dist/agentic/shared/ai/skills/om-system-extension/references/extension-branches.md +25 -0
- package/dist/agentic/shared/ai/skills/om-system-extension/references/mechanism-selector.md +1 -0
- package/dist/agentic/shared/ai/skills/om-system-extension/references/unified-overrides.md +2 -0
- package/dist/agentic/shared/scripts/run-agent-harness-release.mjs +21 -1
- package/dist/lib/cache-provider-manifest.js +9 -0
- package/dist/lib/cache-provider-manifest.js.map +7 -0
- package/dist/lib/generate-watch-plan.js +4 -0
- package/dist/lib/generate-watch-plan.js.map +2 -2
- package/dist/lib/generate-watch-runner.js +1 -0
- package/dist/lib/generate-watch-runner.js.map +2 -2
- package/dist/lib/generate-watch-structure.js +2 -0
- package/dist/lib/generate-watch-structure.js.map +2 -2
- package/dist/lib/generators/ast/writers.js +5 -1
- package/dist/lib/generators/ast/writers.js.map +2 -2
- package/dist/lib/generators/cache-providers.js +80 -0
- package/dist/lib/generators/cache-providers.js.map +7 -0
- package/dist/lib/generators/form-section-ast.js +156 -0
- package/dist/lib/generators/form-section-ast.js.map +7 -0
- package/dist/lib/generators/form-section-extension-compiler.js +568 -0
- package/dist/lib/generators/form-section-extension-compiler.js.map +7 -0
- package/dist/lib/generators/form-section-extension-source.js +245 -0
- package/dist/lib/generators/form-section-extension-source.js.map +7 -0
- package/dist/lib/generators/form-section-runtime-revisions.js +184 -0
- package/dist/lib/generators/form-section-runtime-revisions.js.map +7 -0
- package/dist/lib/generators/form-sections.js +773 -0
- package/dist/lib/generators/form-sections.js.map +7 -0
- package/dist/lib/generators/index.js +2 -0
- package/dist/lib/generators/index.js.map +2 -2
- package/dist/lib/generators/module-entities.js +21 -2
- package/dist/lib/generators/module-entities.js.map +2 -2
- package/dist/lib/generators/module-extension-facts.js +2 -1
- package/dist/lib/generators/module-extension-facts.js.map +2 -2
- package/dist/lib/generators/module-facts.js +30 -1
- package/dist/lib/generators/module-facts.js.map +2 -2
- package/dist/lib/generators/module-override-targets.js +24 -2
- package/dist/lib/generators/module-override-targets.js.map +2 -2
- package/dist/lib/generators/module-registry.js +75 -3
- package/dist/lib/generators/module-registry.js.map +2 -2
- package/dist/lib/generators/openapi.js +27 -17
- package/dist/lib/generators/openapi.js.map +2 -2
- package/dist/lib/post-generate-invalidation.js +20 -1
- package/dist/lib/post-generate-invalidation.js.map +2 -2
- package/dist/lib/resolver.js +195 -1
- package/dist/lib/resolver.js.map +3 -3
- package/dist/lib/single-instance-strategy-guard.js +26 -3
- package/dist/lib/single-instance-strategy-guard.js.map +2 -2
- package/dist/mercato.js +34 -6
- package/dist/mercato.js.map +2 -2
- package/jest.config.cjs +2 -0
- package/package.json +7 -7
- package/src/__tests__/mercato.test.ts +18 -0
- package/src/__tests__/rotation-json-output.test.ts +52 -0
- package/src/lib/__tests__/cache-provider-manifest.test.ts +76 -0
- package/src/lib/__tests__/generate-watch-plan.test.ts +3 -2
- package/src/lib/__tests__/generate-watch-runner.test.ts +13 -1
- package/src/lib/__tests__/generate-watch-structure.test.ts +34 -0
- package/src/lib/__tests__/post-generate-invalidation.test.ts +108 -0
- package/src/lib/__tests__/resolver.form-section-gates.test.ts +82 -0
- package/src/lib/__tests__/single-instance-strategy-guard.test.ts +129 -0
- package/src/lib/cache-provider-manifest.ts +8 -0
- package/src/lib/generate-watch-plan.ts +6 -3
- package/src/lib/generate-watch-runner.ts +1 -0
- package/src/lib/generate-watch-structure.ts +5 -1
- package/src/lib/generators/__tests__/cache-providers.test.ts +102 -0
- package/src/lib/generators/__tests__/derived-crud-route-collisions.test.ts +85 -0
- package/src/lib/generators/__tests__/form-section-outbox.test.ts +53 -0
- package/src/lib/generators/__tests__/form-sections.test.ts +896 -0
- package/src/lib/generators/__tests__/module-extension-facts.test.ts +1 -0
- package/src/lib/generators/__tests__/module-facts.bc-guard.test.ts +8 -6
- package/src/lib/generators/__tests__/module-facts.example-fact-coverage.test.ts +37 -13
- package/src/lib/generators/__tests__/module-facts.local-reference.test.ts +13 -0
- package/src/lib/generators/__tests__/module-override-targets.test.ts +2 -3
- package/src/lib/generators/__tests__/module-subset.test.ts +1 -1
- package/src/lib/generators/__tests__/openapi.test.ts +60 -13
- package/src/lib/generators/__tests__/structural-contracts.test.ts +2 -2
- package/src/lib/generators/ast/writers.ts +6 -1
- package/src/lib/generators/cache-providers.ts +111 -0
- package/src/lib/generators/form-section-ast.ts +166 -0
- package/src/lib/generators/form-section-extension-compiler.ts +632 -0
- package/src/lib/generators/form-section-extension-source.ts +308 -0
- package/src/lib/generators/form-section-runtime-revisions.ts +211 -0
- package/src/lib/generators/form-sections.ts +896 -0
- package/src/lib/generators/index.ts +1 -0
- package/src/lib/generators/module-entities.ts +22 -4
- package/src/lib/generators/module-extension-facts.ts +1 -0
- package/src/lib/generators/module-facts.ts +40 -0
- package/src/lib/generators/module-override-targets.ts +19 -0
- package/src/lib/generators/module-registry.ts +80 -4
- package/src/lib/generators/openapi.ts +31 -20
- package/src/lib/post-generate-invalidation.ts +28 -1
- package/src/lib/resolver.ts +218 -0
- package/src/lib/single-instance-strategy-guard.ts +51 -1
- package/src/mercato.ts +32 -4
- package/dist/agentic/guides/modules/dashboards/incoming-installed-contributions.md +0 -11
|
@@ -0,0 +1,773 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import ts from "typescript-js";
|
|
5
|
+
import { resolveModuleRequirement } from "@open-mercato/shared/modules/module-locators";
|
|
6
|
+
import {
|
|
7
|
+
crudFormSectionClientMutationFactSchema,
|
|
8
|
+
crudSectionOperationMethods as derivedRouteMethods,
|
|
9
|
+
derivedCrudFormSectionClientMutationFact,
|
|
10
|
+
derivedCrudFormSectionRetryPath,
|
|
11
|
+
parseCrudFormSectionClientMutationFacts
|
|
12
|
+
} from "@open-mercato/shared/lib/crud/form-sections/client-mutation-facts";
|
|
13
|
+
import { crudFormSectionOverrideKey } from "@open-mercato/shared/lib/crud/form-sections/composition";
|
|
14
|
+
import { writeGeneratedFile } from "../utils.js";
|
|
15
|
+
import { escapeGeneratedJsonLiteral, stringLiteral } from "./ast/writers.js";
|
|
16
|
+
import { compileCrudFormSectionExtensions } from "./form-section-extension-compiler.js";
|
|
17
|
+
import { parseSectionExtensionSources } from "./form-section-extension-source.js";
|
|
18
|
+
import { arrayField, exportedDeclaration, fieldsOf, helperArgument, literalData, literalValue, readIdentity, unwrap } from "./form-section-ast.js";
|
|
19
|
+
import { hashHandwrittenSectionRuntime, planHandwrittenSectionRevisionWrite } from "./form-section-runtime-revisions.js";
|
|
20
|
+
import {
|
|
21
|
+
MODULE_CODE_EXTENSIONS,
|
|
22
|
+
resolveStandaloneSourceMirrorBase,
|
|
23
|
+
stripModuleCodeExtension
|
|
24
|
+
} from "./scanner.js";
|
|
25
|
+
const factFields = [
|
|
26
|
+
["host", "hostFacts"],
|
|
27
|
+
["contribution", "contributionFacts"]
|
|
28
|
+
];
|
|
29
|
+
const generatedDerivedCrudRouteIndex = "crud-form-section-derived-routes.generated.json";
|
|
30
|
+
function compareIds(left, right) {
|
|
31
|
+
if (left === right) return 0;
|
|
32
|
+
return left < right ? -1 : 1;
|
|
33
|
+
}
|
|
34
|
+
function readRuntimePath(initializer, declaration, declarationSourcePath, expected, invalid) {
|
|
35
|
+
if (!initializer) return invalid("missing runtime loader");
|
|
36
|
+
const arrow = unwrap(helperArgument(initializer, "lazyCrudFormSectionRuntime", invalid));
|
|
37
|
+
if (!ts.isArrowFunction(arrow) || arrow.parameters.length !== 0 || ts.isBlock(arrow.body)) {
|
|
38
|
+
return invalid("expected a zero-argument arrow returning a literal import()");
|
|
39
|
+
}
|
|
40
|
+
const call = unwrap(arrow.body);
|
|
41
|
+
if (!ts.isCallExpression(call) || call.expression.kind !== ts.SyntaxKind.ImportKeyword || call.arguments.length !== 1) {
|
|
42
|
+
return invalid("expected a literal import()");
|
|
43
|
+
}
|
|
44
|
+
const specifier = literalValue(call.arguments[0], "runtime import specifier", invalid);
|
|
45
|
+
if (!specifier.startsWith("./") || specifier.includes("\\")) return invalid("expected a module-relative runtime import");
|
|
46
|
+
const relative = stripModuleCodeExtension(path.posix.normalize(specifier));
|
|
47
|
+
if (relative.startsWith("../") || !relative.endsWith(".client")) {
|
|
48
|
+
return invalid(`runtime import "${specifier}" must resolve to a .client file inside the owning module`);
|
|
49
|
+
}
|
|
50
|
+
const readRuntime = (declarationPath) => {
|
|
51
|
+
const owner = path.dirname(declarationPath);
|
|
52
|
+
const runtimeFile = MODULE_CODE_EXTENSIONS.map((extension) => path.join(owner, `${relative}${extension}`)).find((candidate) => fs.existsSync(candidate));
|
|
53
|
+
if (!runtimeFile) return invalid(`runtime import "${specifier}" is missing from the owning module`);
|
|
54
|
+
const filename = fs.realpathSync(runtimeFile);
|
|
55
|
+
const fromOwner = path.relative(fs.realpathSync(owner), filename);
|
|
56
|
+
if (fromOwner === ".." || fromOwner.startsWith(`..${path.sep}`) || path.isAbsolute(fromOwner)) {
|
|
57
|
+
return invalid(`runtime import "${specifier}" escapes the owning module`);
|
|
58
|
+
}
|
|
59
|
+
const source2 = ts.createSourceFile(filename, fs.readFileSync(filename, "utf8"), ts.ScriptTarget.Latest, true);
|
|
60
|
+
const runtime = exportedDeclaration(source2, "crudFormSectionRuntime");
|
|
61
|
+
if (!runtime) return invalid(`runtime import "${specifier}" must export crudFormSectionRuntime`);
|
|
62
|
+
const runtimeValue = unwrap(runtime);
|
|
63
|
+
const literal = ts.isCallExpression(runtimeValue) ? helperArgument(
|
|
64
|
+
runtimeValue,
|
|
65
|
+
ts.isIdentifier(runtimeValue.expression) && runtimeValue.expression.text === "defineCrudFormFieldGranularSection" ? "defineCrudFormFieldGranularSection" : "defineCrudFormSectionRuntime",
|
|
66
|
+
invalid
|
|
67
|
+
) : runtimeValue;
|
|
68
|
+
const actual = readIdentity(fieldsOf(literal, invalid), invalid);
|
|
69
|
+
if (actual.id !== expected.id || actual.roundTripId !== expected.roundTripId) {
|
|
70
|
+
return invalid(`runtime import "${specifier}" exports "${actual.roundTripId}" but loader declares "${expected.roundTripId}"`);
|
|
71
|
+
}
|
|
72
|
+
return source2;
|
|
73
|
+
};
|
|
74
|
+
const source = readRuntime(declarationSourcePath);
|
|
75
|
+
if (declarationSourcePath !== declaration.absolutePath) readRuntime(declaration.absolutePath);
|
|
76
|
+
const importBase = declaration.importPath.slice(0, declaration.importPath.lastIndexOf("/"));
|
|
77
|
+
return { runtimePath: `${importBase}/${relative}`, source };
|
|
78
|
+
}
|
|
79
|
+
function importedNamedBinding(source, localName) {
|
|
80
|
+
for (const statement of source.statements) {
|
|
81
|
+
if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier) || statement.importClause?.isTypeOnly) continue;
|
|
82
|
+
const names = statement.importClause?.namedBindings;
|
|
83
|
+
if (!names || !ts.isNamedImports(names)) continue;
|
|
84
|
+
const entry = names.elements.find(({ name, isTypeOnly }) => !isTypeOnly && name.text === localName);
|
|
85
|
+
if (entry) return { specifier: statement.moduleSpecifier.text, exported: (entry.propertyName ?? entry.name).text };
|
|
86
|
+
}
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
function exportsFactoryBinding(source, factoryName, exported) {
|
|
90
|
+
const exportedLocals = /* @__PURE__ */ new Set();
|
|
91
|
+
for (const statement of source.statements) {
|
|
92
|
+
if (!ts.isExportDeclaration(statement) || statement.moduleSpecifier || !statement.exportClause || !ts.isNamedExports(statement.exportClause)) continue;
|
|
93
|
+
for (const entry of statement.exportClause.elements) {
|
|
94
|
+
if (!entry.isTypeOnly && entry.name.text === exported) exportedLocals.add((entry.propertyName ?? entry.name).text);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
for (const statement of source.statements) {
|
|
98
|
+
if (!ts.isVariableStatement(statement)) continue;
|
|
99
|
+
const direct = statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword);
|
|
100
|
+
const isBound = (local) => Boolean(direct && local === exported) || exportedLocals.has(local);
|
|
101
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
102
|
+
if (!declaration.initializer) continue;
|
|
103
|
+
const value = unwrap(declaration.initializer);
|
|
104
|
+
if (ts.isIdentifier(declaration.name) && isBound(declaration.name.text) && ts.isPropertyAccessExpression(value) && ts.isIdentifier(value.expression) && value.expression.text === factoryName && value.name.text === exported) return true;
|
|
105
|
+
if (ts.isObjectBindingPattern(declaration.name) && ts.isIdentifier(value) && value.text === factoryName && declaration.name.elements.some((entry) => ts.isIdentifier(entry.name) && isBound(entry.name.text) && !entry.initializer && (entry.propertyName ?? entry.name).getText() === exported)) return true;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
function hasIdentityMapper(input) {
|
|
111
|
+
if (!input) return true;
|
|
112
|
+
const mapper = unwrap(input);
|
|
113
|
+
if (!ts.isArrowFunction(mapper) || mapper.parameters.length !== 1 || ts.isBlock(mapper.body)) return false;
|
|
114
|
+
const binding = mapper.parameters[0].name;
|
|
115
|
+
if (!ts.isObjectBindingPattern(binding) || binding.elements.length !== 1) return false;
|
|
116
|
+
const [entry] = binding.elements;
|
|
117
|
+
const body = unwrap(mapper.body);
|
|
118
|
+
return !entry.dotDotDotToken && !entry.initializer && ts.isIdentifier(entry.name) && (entry.propertyName ?? entry.name).getText() === "parsed" && ts.isIdentifier(body) && body.text === entry.name.text;
|
|
119
|
+
}
|
|
120
|
+
function parseDerivedRoutes(fields, module, declaration, source, invalid) {
|
|
121
|
+
return arrayField(fields, "derivedHosts", invalid).map((entry, index) => {
|
|
122
|
+
const options = fieldsOf(helperArgument(entry, "defineCrudRouteSectionHost", invalid), invalid);
|
|
123
|
+
const hostDescriptorId = literalValue(options.get("hostDescriptorId"), "hostDescriptorId", invalid);
|
|
124
|
+
const formOperation = literalValue(options.get("formOperation"), "formOperation", invalid);
|
|
125
|
+
if (formOperation !== "create" && formOperation !== "update") return invalid("derived host requires create or update");
|
|
126
|
+
if (formOperation === "create" && options.has("delete")) return invalid("derived create host cannot declare delete");
|
|
127
|
+
const groups = arrayField(options, "sections", invalid);
|
|
128
|
+
if (!groups.length) return invalid("derived host requires a finite group set");
|
|
129
|
+
for (const group of groups) {
|
|
130
|
+
const writes = literalValue(fieldsOf(group, invalid).get("writes"), "section writes", invalid);
|
|
131
|
+
if (writes !== "parent" && writes !== "none") return invalid("derived host group declares a secondary write");
|
|
132
|
+
}
|
|
133
|
+
const routeNode = options.get("route");
|
|
134
|
+
const binding = routeNode && ts.isIdentifier(routeNode) && importedNamedBinding(source, routeNode.text);
|
|
135
|
+
if (!binding || !/^\.\/api(?:\/[A-Za-z0-9_.[\]-]+)*\/route(?:\.[jt]sx?)?$/.test(binding.specifier)) {
|
|
136
|
+
return invalid("derived host route must import the original named makeCrudRoute result from its module API route");
|
|
137
|
+
}
|
|
138
|
+
const relative = binding.specifier.slice(2);
|
|
139
|
+
const routeFile = module.resolve(relative);
|
|
140
|
+
if (!routeFile || routeFile.fromApp !== declaration.fromApp) return invalid("derived host route is missing or shadowed");
|
|
141
|
+
const mirror = routeFile.fromApp ? null : resolveStandaloneSourceMirrorBase(module.roots.pkgBase);
|
|
142
|
+
const mirrorFile = mirror && MODULE_CODE_EXTENSIONS.map(
|
|
143
|
+
(extension) => path.join(mirror, stripModuleCodeExtension(relative) + extension)
|
|
144
|
+
).find((candidate) => fs.existsSync(candidate));
|
|
145
|
+
const fileName = mirrorFile || routeFile.absolutePath;
|
|
146
|
+
const routeSource = ts.createSourceFile(fileName, fs.readFileSync(fileName, "utf8"), ts.ScriptTarget.Latest, true);
|
|
147
|
+
const routeInitializer = exportedDeclaration(routeSource, binding.exported);
|
|
148
|
+
const routeCall = routeInitializer && unwrap(routeInitializer);
|
|
149
|
+
const factory = routeCall && ts.isCallExpression(routeCall) && ts.isIdentifier(routeCall.expression) && importedNamedBinding(routeSource, routeCall.expression.text);
|
|
150
|
+
if (!routeCall || !ts.isCallExpression(routeCall) || routeCall.arguments.length !== 1 || !factory || factory.exported !== "makeCrudRoute" || !["@open-mercato/shared/lib/crud/factory", "@open-mercato/shared/lib/crud"].includes(factory.specifier)) {
|
|
151
|
+
return invalid("derived host requires a named original makeCrudRoute declaration");
|
|
152
|
+
}
|
|
153
|
+
const routeDeclaration = routeInitializer?.parent;
|
|
154
|
+
if (!routeDeclaration || !ts.isVariableDeclaration(routeDeclaration) || !ts.isIdentifier(routeDeclaration.name) || !exportsFactoryBinding(routeSource, routeDeclaration.name.text, "metadata")) {
|
|
155
|
+
return invalid("derived route metadata must come directly from the named factory result");
|
|
156
|
+
}
|
|
157
|
+
const factoryName = routeDeclaration.name.text;
|
|
158
|
+
const factoryOptions = fieldsOf(routeCall.arguments[0], invalid);
|
|
159
|
+
const actionNode = factoryOptions.get("actions");
|
|
160
|
+
const metadataNode = factoryOptions.get("metadata");
|
|
161
|
+
if (!actionNode || !metadataNode) return invalid("derived route requires literal factory actions and method metadata");
|
|
162
|
+
if (factoryOptions.has("resolveIdentifiers")) return invalid("derived route declares custom identifier mapping");
|
|
163
|
+
const hooks = factoryOptions.get("hooks");
|
|
164
|
+
if (hooks && [...fieldsOf(hooks, invalid).keys()].some((key) => /^(before|after)(Create|Update|Delete)$/.test(key))) {
|
|
165
|
+
return invalid("derived route declares custom write hooks");
|
|
166
|
+
}
|
|
167
|
+
const actions = fieldsOf(actionNode, invalid);
|
|
168
|
+
const metadata = fieldsOf(metadataNode, invalid);
|
|
169
|
+
const operations = [formOperation, ...options.has("delete") ? ["delete"] : []];
|
|
170
|
+
for (const operation of operations) {
|
|
171
|
+
const action = actions.get(operation);
|
|
172
|
+
const method = derivedRouteMethods[operation];
|
|
173
|
+
if (!action || !metadata.has(method) || !exportsFactoryBinding(routeSource, factoryName, method)) {
|
|
174
|
+
return invalid(`derived route has no direct ${method} factory export, command or metadata`);
|
|
175
|
+
}
|
|
176
|
+
const command = fieldsOf(action, invalid);
|
|
177
|
+
if (!hasIdentityMapper(command.get("mapInput")) || command.has("metadata")) {
|
|
178
|
+
return invalid(`derived ${method} route requires direct command input without custom metadata`);
|
|
179
|
+
}
|
|
180
|
+
const commandId = literalValue(command.get("commandId"), "commandId", invalid);
|
|
181
|
+
if (!commandId.endsWith(`.${operation}`)) return invalid(`derived ${method} route command does not match its operation`);
|
|
182
|
+
const methodMetadata = fieldsOf(metadata.get(method), invalid);
|
|
183
|
+
if (methodMetadata.get("requireAuth")?.kind !== ts.SyntaxKind.TrueKeyword || methodMetadata.has("requireRoles")) {
|
|
184
|
+
return invalid(`derived ${method} route must require authentication`);
|
|
185
|
+
}
|
|
186
|
+
for (const feature of arrayField(methodMetadata, "requireFeatures", invalid)) literalValue(feature, "required feature", invalid);
|
|
187
|
+
}
|
|
188
|
+
const configuredPath = metadata.get("path");
|
|
189
|
+
const basePath = configuredPath ? literalValue(configuredPath, "route path", invalid) : `/${[module.modId, ...relative.split("/").slice(1, -1)].join("/")}`;
|
|
190
|
+
if (!/^\/(?:[A-Za-z0-9_.-]+|\[[A-Za-z0-9_-]+\])(?:\/(?:[A-Za-z0-9_.-]+|\[[A-Za-z0-9_-]+\]))*$/.test(basePath)) {
|
|
191
|
+
return invalid("derived route path must be a regular named API path");
|
|
192
|
+
}
|
|
193
|
+
const outboxRetry = options.has("outboxRetry");
|
|
194
|
+
if (outboxRetry && (formOperation !== "update" || options.get("outboxRetry")?.kind !== ts.SyntaxKind.TrueKeyword)) {
|
|
195
|
+
return invalid("derived outbox retry must literally opt in on an update host");
|
|
196
|
+
}
|
|
197
|
+
const versioned = options.has("expectedVersionField");
|
|
198
|
+
if (versioned) literalValue(options.get("expectedVersionField"), "expectedVersionField", invalid);
|
|
199
|
+
return { index, routePath: `${basePath}/section-policy`, hostDescriptorId, operations, versioned, outboxRetry };
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
function parseModuleSections(module, checkRevisions = false) {
|
|
203
|
+
const declaration = module.resolve("form-sections.ts");
|
|
204
|
+
if (!declaration) return null;
|
|
205
|
+
const mirror = declaration.fromApp ? null : resolveStandaloneSourceMirrorBase(module.roots.pkgBase);
|
|
206
|
+
const sourceFile = mirror && fs.existsSync(path.join(mirror, "form-sections.ts")) ? path.join(mirror, "form-sections.ts") : declaration.absolutePath;
|
|
207
|
+
const source = ts.createSourceFile(sourceFile, fs.readFileSync(sourceFile, "utf8"), ts.ScriptTarget.Latest, true);
|
|
208
|
+
const invalid = (reason) => {
|
|
209
|
+
throw new Error(`[generate] form-sections for "${module.modId}" (${sourceFile}): ${reason}`);
|
|
210
|
+
};
|
|
211
|
+
for (const statement of source.statements) {
|
|
212
|
+
if (!ts.isImportDeclaration(statement) || statement.importClause?.isTypeOnly || !ts.isStringLiteralLike(statement.moduleSpecifier)) continue;
|
|
213
|
+
const specifier = statement.moduleSpecifier.text;
|
|
214
|
+
if (/^(?:react(?:-dom)?|next)(?:\/|$)/.test(specifier) || /(?:\.client(?:\.[jt]sx?)?|\/page(?:\.[jt]sx?)?)$/.test(specifier)) {
|
|
215
|
+
invalid(`server declaration statically imports "${specifier}"`);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
const initializer = exportedDeclaration(source, "crudFormSections");
|
|
219
|
+
const extensionExport = exportedDeclaration(source, "crudFormExtensions");
|
|
220
|
+
if (!initializer && !extensionExport) return invalid("expected a named crudFormSections or crudFormExtensions declaration");
|
|
221
|
+
const moduleBase = path.dirname(sourceFile);
|
|
222
|
+
const extensions = parseSectionExtensionSources(extensionExport, moduleBase, declaration.importPath, invalid);
|
|
223
|
+
const fields = initializer ? fieldsOf(helperArgument(initializer, "defineCrudFormSections", invalid), invalid) : /* @__PURE__ */ new Map();
|
|
224
|
+
const derivedRoutes = parseDerivedRoutes(fields, module, declaration, source, invalid);
|
|
225
|
+
const runtimes = /* @__PURE__ */ new Map();
|
|
226
|
+
for (const runtime of arrayField(fields, "runtimes", invalid)) {
|
|
227
|
+
const properties = fieldsOf(runtime, invalid);
|
|
228
|
+
const { id, roundTripId } = readIdentity(properties, invalid);
|
|
229
|
+
if (runtimes.has(id)) invalid(`duplicate runtime loader id "${id}"`);
|
|
230
|
+
runtimes.set(id, { roundTripId, ...readRuntimePath(properties.get("load"), declaration, sourceFile, { id, roundTripId }, invalid) });
|
|
231
|
+
}
|
|
232
|
+
const leafDefaultProviderIds = arrayField(fields, "leafDefaultProviders", invalid).map((entry) => {
|
|
233
|
+
const provider = unwrap(entry);
|
|
234
|
+
if (!ts.isObjectLiteralExpression(provider)) return invalid("expected a leaf default provider object");
|
|
235
|
+
const factProperty = provider.properties.find((property) => ts.isPropertyAssignment(property) && (ts.isIdentifier(property.name) || ts.isStringLiteralLike(property.name)) && property.name.text === "fact");
|
|
236
|
+
if (!factProperty) return invalid("missing literal leaf default provider fact");
|
|
237
|
+
literalData(factProperty.initializer, invalid);
|
|
238
|
+
return readIdentity(fieldsOf(factProperty.initializer, invalid), invalid).id;
|
|
239
|
+
}).sort(compareIds);
|
|
240
|
+
const sinkIds = arrayField(fields, "sinks", invalid).map((entry) => {
|
|
241
|
+
const call = unwrap(entry);
|
|
242
|
+
const isOutboxBuilder = ts.isCallExpression(call) && ts.isIdentifier(call.expression) && call.expression.text === "defineCrudFormSectionOutboxSink";
|
|
243
|
+
const declaration2 = unwrap(helperArgument(entry, isOutboxBuilder ? "defineCrudFormSectionOutboxSink" : "defineCrudFormSectionSink", invalid));
|
|
244
|
+
if (!ts.isObjectLiteralExpression(declaration2)) return invalid("expected a sink declaration object");
|
|
245
|
+
const fact = declaration2.properties.find((property) => ts.isPropertyAssignment(property) && (ts.isIdentifier(property.name) || ts.isStringLiteralLike(property.name)) && property.name.text === "fact");
|
|
246
|
+
if (!fact) return invalid("missing literal sink fact");
|
|
247
|
+
const properties = fieldsOf(fact.initializer, invalid);
|
|
248
|
+
const { id } = readIdentity(properties, invalid);
|
|
249
|
+
literalData(fact.initializer, invalid);
|
|
250
|
+
if (literalValue(properties.get("ownerModuleId"), "ownerModuleId", invalid) !== module.modId) {
|
|
251
|
+
return invalid(`sink "${id}" must be declared in its owning module`);
|
|
252
|
+
}
|
|
253
|
+
const atomicity = literalValue(properties.get("atomicity"), "atomicity", invalid);
|
|
254
|
+
const externalDelivery = properties.get("externalDelivery");
|
|
255
|
+
if (atomicity === "outbox") {
|
|
256
|
+
if (!externalDelivery) return invalid(`outbox sink "${id}" requires a literal externalDelivery contract`);
|
|
257
|
+
const external = fieldsOf(externalDelivery, invalid);
|
|
258
|
+
const maxAttempts = external.get("maxAttempts");
|
|
259
|
+
const attempts = maxAttempts && literalData(maxAttempts, invalid);
|
|
260
|
+
const target = literalValue(properties.get("targetEntityId"), "targetEntityId", invalid);
|
|
261
|
+
const contract = literalValue(external.get("contractId"), "contractId", invalid);
|
|
262
|
+
if (!contract.startsWith(`${target}@v`) || !/^[1-9][0-9]*$/.test(contract.slice(target.length + 2))) {
|
|
263
|
+
return invalid(`outbox sink "${id}" requires contractId "${target}@v<positive-integer>"`);
|
|
264
|
+
}
|
|
265
|
+
if (external.size !== 6 || literalValue(external.get("fencing"), "fencing", invalid) !== "remote-monotonic-revision/v1" || literalValue(external.get("coalesce"), "coalesce", invalid) !== "latest-state" || !["none", "read-only"].includes(literalValue(external.get("preCommitValidation"), "preCommitValidation", invalid)) || !literalValue(external.get("integrationId"), "integrationId", invalid) || typeof attempts !== "number" || !Number.isSafeInteger(attempts) || attempts < 1) {
|
|
266
|
+
return invalid(`outbox sink "${id}" requires the remote-monotonic-revision/v1 fencing contract`);
|
|
267
|
+
}
|
|
268
|
+
} else if (!["host-transaction", "after-commit"].includes(atomicity) || externalDelivery || isOutboxBuilder) {
|
|
269
|
+
return invalid(`invalid atomicity or externalDelivery for sink "${id}"`);
|
|
270
|
+
}
|
|
271
|
+
return id;
|
|
272
|
+
}).sort(compareIds);
|
|
273
|
+
const descriptors = [];
|
|
274
|
+
const primitiveContributions = [];
|
|
275
|
+
const authoredSource = !moduleBase.split(path.sep).includes("node_modules") && (declaration.fromApp || !moduleBase.split(path.sep).includes("dist"));
|
|
276
|
+
const revisions = [];
|
|
277
|
+
const clientHosts = [];
|
|
278
|
+
const customFieldSeedEntities = /* @__PURE__ */ new Map();
|
|
279
|
+
const factIds = /* @__PURE__ */ new Set();
|
|
280
|
+
for (const [kind, field] of factFields) {
|
|
281
|
+
const facts = arrayField(fields, field, invalid);
|
|
282
|
+
for (const [index, fact] of facts.entries()) {
|
|
283
|
+
const properties = fieldsOf(fact, invalid);
|
|
284
|
+
const { id, roundTripId } = readIdentity(properties, invalid);
|
|
285
|
+
if (kind === "host") {
|
|
286
|
+
const seeds = properties.get("customFieldSeedEntities");
|
|
287
|
+
if (seeds) {
|
|
288
|
+
customFieldSeedEntities.set(id, Object.fromEntries([...fieldsOf(seeds, invalid)].map(([setId, value]) => {
|
|
289
|
+
const entityId = literalValue(value, "custom-field seed entity", invalid);
|
|
290
|
+
if (!/^[a-z0-9][a-z0-9._-]*$/.test(setId) || !/^[a-z0-9_]+:[a-z0-9_]+$/.test(entityId)) {
|
|
291
|
+
return invalid("customFieldSeedEntities requires literal definition-set and entity ids");
|
|
292
|
+
}
|
|
293
|
+
return [setId, entityId];
|
|
294
|
+
})));
|
|
295
|
+
}
|
|
296
|
+
const hostResourceKind = properties.has("hostResourceKind") ? literalValue(properties.get("hostResourceKind"), "hostResourceKind", invalid) : void 0;
|
|
297
|
+
const alternatives = arrayField(properties, "alternatives", invalid).map((entry) => {
|
|
298
|
+
const alternative = fieldsOf(entry, invalid);
|
|
299
|
+
const surface = alternative.get("surface");
|
|
300
|
+
if (!surface) return invalid("missing finite surface alternative");
|
|
301
|
+
const fact2 = literalData(surface, invalid);
|
|
302
|
+
if (!fact2 || typeof fact2 !== "object" || Array.isArray(fact2)) return invalid("expected finite surface facts");
|
|
303
|
+
const derived = derivedRoutes.find(({ hostDescriptorId }) => hostDescriptorId === id);
|
|
304
|
+
if (Object.hasOwn(fact2, "clientMutationSurfaces")) return invalid("client mutation surface projection is generated");
|
|
305
|
+
if ("allowNoopSubmit" in fact2 && typeof fact2.allowNoopSubmit !== "boolean") return invalid("allowNoopSubmit must be a boolean");
|
|
306
|
+
const authoredIds = fact2.mutationSurfaceIds;
|
|
307
|
+
if (!Array.isArray(authoredIds) || authoredIds.some((surfaceId) => typeof surfaceId !== "string")) {
|
|
308
|
+
return invalid("mutationSurfaceIds must be a literal ID array");
|
|
309
|
+
}
|
|
310
|
+
const rows = derived ? derived.operations.map((operation) => derivedCrudFormSectionClientMutationFact({
|
|
311
|
+
operation,
|
|
312
|
+
hostDescriptorId: id,
|
|
313
|
+
route: derived.routePath,
|
|
314
|
+
versioned: derived.versioned,
|
|
315
|
+
resourceKind: hostResourceKind ?? ""
|
|
316
|
+
})) : arrayField(alternative, "mutationSurfaces", invalid).map((mutation) => {
|
|
317
|
+
const declaration2 = fieldsOf(mutation, invalid);
|
|
318
|
+
return Object.fromEntries(Object.keys(crudFormSectionClientMutationFactSchema.shape).flatMap((key) => {
|
|
319
|
+
const value = declaration2.get(key);
|
|
320
|
+
return value ? [[key, literalData(value, invalid)]] : [];
|
|
321
|
+
}));
|
|
322
|
+
});
|
|
323
|
+
const mutationSurfaceIds = derived ? derived.operations.map((operation) => `${id}.${operation}`) : authoredIds;
|
|
324
|
+
const clientMutationSurfaces = parseCrudFormSectionClientMutationFacts(mutationSurfaceIds, rows);
|
|
325
|
+
if (!clientMutationSurfaces || clientMutationSurfaces.some((row) => row.hostResourceKind !== hostResourceKind)) {
|
|
326
|
+
return invalid("mutation surface projection does not match its host alternative");
|
|
327
|
+
}
|
|
328
|
+
return {
|
|
329
|
+
...fact2,
|
|
330
|
+
mutationSurfaceIds,
|
|
331
|
+
...clientMutationSurfaces.length ? { clientMutationSurfaces } : {}
|
|
332
|
+
};
|
|
333
|
+
});
|
|
334
|
+
if (alternatives.length && !hostResourceKind) return invalid("host alternatives require a hostResourceKind");
|
|
335
|
+
clientHosts.push({ id, roundTripId, hostResourceKind, alternatives });
|
|
336
|
+
}
|
|
337
|
+
const addressNode = properties.get("address");
|
|
338
|
+
const operationNode = properties.get("operation");
|
|
339
|
+
if (kind === "contribution" && addressNode && operationNode && ts.isObjectLiteralExpression(unwrap(addressNode))) {
|
|
340
|
+
const operation = unwrap(operationNode);
|
|
341
|
+
const literalAddress = unwrap(addressNode);
|
|
342
|
+
const address = Object.fromEntries(literalAddress.properties.flatMap((property) => {
|
|
343
|
+
if (!ts.isPropertyAssignment(property) || !ts.isIdentifier(property.name) && !ts.isStringLiteralLike(property.name)) return [];
|
|
344
|
+
const value = unwrap(property.initializer);
|
|
345
|
+
return ts.isStringLiteralLike(value) ? [[property.name.text, value.text]] : [];
|
|
346
|
+
}));
|
|
347
|
+
const { hostId, formVariant, formOperation, sectionId } = address;
|
|
348
|
+
if (hostId && formVariant && sectionId && (formOperation === "create" || formOperation === "update") && ts.isStringLiteralLike(operation) && (operation.text === "add" || operation.text === "replace" || operation.text === "hide")) {
|
|
349
|
+
primitiveContributions.push({ id, address: { hostId, formVariant, formOperation, sectionId }, operation: operation.text });
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
if (factIds.has(id)) invalid(`duplicate fact id "${id}"`);
|
|
353
|
+
factIds.add(id);
|
|
354
|
+
const runtime = runtimes.get(id);
|
|
355
|
+
if (!runtime) return invalid(`fact "${id}" has no matching runtime loader`);
|
|
356
|
+
if (runtime.roundTripId !== roundTripId) {
|
|
357
|
+
invalid(`fact and runtime roundTripId differ for "${id}"`);
|
|
358
|
+
}
|
|
359
|
+
descriptors.push({ id, roundTripId, kind, field, index, runtimePath: runtime.runtimePath });
|
|
360
|
+
if (checkRevisions && authoredSource) {
|
|
361
|
+
revisions.push({ id, roundTripId, sourceHash: hashHandwrittenSectionRuntime(runtime.source, fact, moduleBase) });
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
for (const id of runtimes.keys()) {
|
|
366
|
+
if (!factIds.has(id)) invalid(`runtime loader "${id}" has no matching fact`);
|
|
367
|
+
}
|
|
368
|
+
return {
|
|
369
|
+
moduleId: module.modId,
|
|
370
|
+
importPath: declaration.importPath,
|
|
371
|
+
hasHandwrittenSections: Boolean(initializer),
|
|
372
|
+
sourceFileName: path.basename(sourceFile),
|
|
373
|
+
sourceBase: moduleBase,
|
|
374
|
+
authoredSource,
|
|
375
|
+
extensionSources: extensions,
|
|
376
|
+
runtimeSources: runtimes,
|
|
377
|
+
customFieldSeedEntities,
|
|
378
|
+
primitiveContributions,
|
|
379
|
+
derivedRoutes,
|
|
380
|
+
clientHosts: clientHosts.sort((left, right) => compareIds(left.id, right.id)),
|
|
381
|
+
contributedOverrides: fields.has("contributedOverrides") ? literalData(fields.get("contributedOverrides"), invalid) : {},
|
|
382
|
+
leafDefaultProviderIds,
|
|
383
|
+
sinkIds,
|
|
384
|
+
revisionWrite: planHandwrittenSectionRevisionWrite(moduleBase, revisions, invalid),
|
|
385
|
+
descriptors: descriptors.sort((left, right) => compareIds(left.id, right.id))
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
function orderedSectionModules(sections, identities, requiresByModule) {
|
|
389
|
+
const done = /* @__PURE__ */ new Set();
|
|
390
|
+
const visiting = /* @__PURE__ */ new Set();
|
|
391
|
+
const ordered = [];
|
|
392
|
+
function visit(moduleId) {
|
|
393
|
+
if (done.has(moduleId)) return;
|
|
394
|
+
if (visiting.has(moduleId)) {
|
|
395
|
+
throw new Error(`[generate] Cannot order form-sections through a module dependency cycle at "${moduleId}"`);
|
|
396
|
+
}
|
|
397
|
+
visiting.add(moduleId);
|
|
398
|
+
const dependencies = (requiresByModule.get(moduleId) ?? []).map((requirement) => resolveModuleRequirement(requirement, identities)).filter((dependency) => dependency !== void 0).sort(compareIds);
|
|
399
|
+
for (const dependency of dependencies) visit(dependency);
|
|
400
|
+
visiting.delete(moduleId);
|
|
401
|
+
done.add(moduleId);
|
|
402
|
+
const module = sections.get(moduleId);
|
|
403
|
+
if (module) ordered.push(module);
|
|
404
|
+
}
|
|
405
|
+
const sectionModules = [...sections.values()].sort((left, right) => compareIds(left.importPath, right.importPath));
|
|
406
|
+
for (const module of sectionModules) visit(module.moduleId);
|
|
407
|
+
return ordered;
|
|
408
|
+
}
|
|
409
|
+
const generatedHeader = "// Auto-generated by yarn generate. Do not edit.";
|
|
410
|
+
const injectionPositionTypeImport = "import type { InjectionPosition } from '@open-mercato/shared/modules/widgets/injection-position'";
|
|
411
|
+
function renderSectionOverrides(overrides) {
|
|
412
|
+
return escapeGeneratedJsonLiteral(JSON.stringify(overrides, null, 2)).replace(/^( +"position": "(?:first|last|before|after)")/gm, "$1 as InjectionPosition");
|
|
413
|
+
}
|
|
414
|
+
function renderFactRegistry(modules, compiled) {
|
|
415
|
+
const hasGenericSinks = [...compiled.contributionsByModule.values()].some((entries2) => entries2.some(({ sinks }) => sinks.some(({ fields }) => fields.some(({ field }) => field.store?.kind === "table" || field.store?.kind === "external"))));
|
|
416
|
+
const moduleIndexes = new Map(modules.map(({ moduleId }, index) => [moduleId, index]));
|
|
417
|
+
const imports = modules.flatMap(({ importPath, hasHandwrittenSections, extensionSources }, index) => [
|
|
418
|
+
...hasHandwrittenSections ? [`import { crudFormSections as sections${index} } from ${JSON.stringify(importPath)}`] : [],
|
|
419
|
+
...extensionSources.length ? [`import { crudFormExtensions as extensions${index} } from ${JSON.stringify(importPath)}`] : []
|
|
420
|
+
]);
|
|
421
|
+
const authoredSection = ({ module, extension, change }) => `extensions${moduleIndexes.get(module.moduleId)}[${extension.index}].sections[${JSON.stringify(change.id)}]`;
|
|
422
|
+
const compiledDeclarations = modules.flatMap(({ moduleId }, index) => {
|
|
423
|
+
const candidates = compiled.contributionsByModule.get(moduleId);
|
|
424
|
+
if (!candidates?.length) return [];
|
|
425
|
+
const lines = candidates.map(({ contribution, fields, defaults, sinks }) => {
|
|
426
|
+
const compiledFields = fields.flatMap(({ field, authored, payloadPath }) => {
|
|
427
|
+
if (!payloadPath || !field.server && !field.rules.some(({ enforce }) => enforce === "client-and-server")) return [];
|
|
428
|
+
const source = `${authoredSection(authored)}.options.fields[${JSON.stringify(field.id)}].${field.operation === "add" ? "definition" : "patch"}`;
|
|
429
|
+
const data = JSON.stringify({ fieldId: field.id, payloadPath, rules: field.rules });
|
|
430
|
+
return [`{ ...${data}${field.server ? `, server: ${source}.validate.server` : ""} }`];
|
|
431
|
+
});
|
|
432
|
+
function fieldStore({ field, authored, payloadPath }) {
|
|
433
|
+
const source = authoredSection(authored);
|
|
434
|
+
if (field.store?.fieldOverride) return `${source}.options.fields[${JSON.stringify(field.id)}].definition.store`;
|
|
435
|
+
if (authored.change.operation === "add" && field.store?.kind !== "customField") return `${source}.options.store`;
|
|
436
|
+
return `{ kind: 'customField', key: ${JSON.stringify(payloadPath?.slice("customFields.".length))} }`;
|
|
437
|
+
}
|
|
438
|
+
const stores = fields.flatMap((item) => {
|
|
439
|
+
const { field, authored, payloadPath, customField } = item;
|
|
440
|
+
if (!payloadPath || !field.store) return [];
|
|
441
|
+
const data = JSON.stringify({ ownerModuleId: authored.module.moduleId, fieldId: field.id, payloadPath, customField });
|
|
442
|
+
return [`{ ...${data}, store: ${fieldStore(item)} }`];
|
|
443
|
+
});
|
|
444
|
+
const sinkAssociations = sinks.map(({ fields: owned, ...keys }) => {
|
|
445
|
+
const [{ authored }] = owned;
|
|
446
|
+
const plan = {
|
|
447
|
+
...keys,
|
|
448
|
+
ownerModuleId: authored.module.moduleId,
|
|
449
|
+
payloadPaths: owned.map(({ payloadPath }) => payloadPath),
|
|
450
|
+
fields: owned.map(({ field }) => ({
|
|
451
|
+
key: field.id,
|
|
452
|
+
kind: field.browser.type,
|
|
453
|
+
required: field.browser.required,
|
|
454
|
+
options: Array.isArray(field.browser.options) ? field.browser.options.map(({ value }) => value) : void 0
|
|
455
|
+
}))
|
|
456
|
+
};
|
|
457
|
+
const kind = owned[0].field.store?.kind;
|
|
458
|
+
const entityProof = kind === "table" || kind === "external" ? `, entityExports: lookupCompiledOrmExports(${JSON.stringify(authored.module.moduleId)})` : "";
|
|
459
|
+
return `{ ...${JSON.stringify(plan)}, store: ${fieldStore(owned[0])}${entityProof} }`;
|
|
460
|
+
});
|
|
461
|
+
const providers = defaults.map(({ owner, id, payloadPath, readsPayloadPaths, scoped }) => {
|
|
462
|
+
const { hostId, formVariant, formOperation } = contribution.address;
|
|
463
|
+
const fact = { id, roundTripId: `${id}@v${contribution.roundTripId.split("@v")[1]}`, hostId, formVariant, formOperation, payloadPath, readsPayloadPaths };
|
|
464
|
+
return `{ fact: ${JSON.stringify(fact)}, resolve: extensions${moduleIndexes.get(owner.module.moduleId)}[${owner.extension.index}].defaults[${JSON.stringify(payloadPath)}]${scoped ? ".resolve" : ""} }`;
|
|
465
|
+
});
|
|
466
|
+
return ` { contribution: ${JSON.stringify(contribution)}, fieldRules: [${compiledFields.join(", ")}], defaults: [${providers.join(", ")}], stores: [${stores.join(", ")}], sinkAssociations: [${sinkAssociations.join(", ")}] },`;
|
|
467
|
+
});
|
|
468
|
+
const overrides = Object.fromEntries(Object.entries(compiled.fallbacks).filter(([, override]) => candidates.some(({ id }) => id === override?.contributionId)));
|
|
469
|
+
return [
|
|
470
|
+
`const compiled${index} = [`,
|
|
471
|
+
...lines,
|
|
472
|
+
"] as const satisfies readonly CompiledCrudFormContribution[]",
|
|
473
|
+
`const compiledOverrides${index} = ${renderSectionOverrides(overrides)} as const`
|
|
474
|
+
];
|
|
475
|
+
});
|
|
476
|
+
const entries = modules.flatMap(({ moduleId, descriptors }, index) => [
|
|
477
|
+
...descriptors.map(
|
|
478
|
+
(descriptor) => ` { kind: ${JSON.stringify(descriptor.kind)}, moduleId: ${JSON.stringify(moduleId)}, fact: sections${index}.${descriptor.field}[${descriptor.index}] },`
|
|
479
|
+
),
|
|
480
|
+
...(compiled.contributionsByModule.get(moduleId) ?? []).map((_, contribution) => ` { kind: "contribution", moduleId: ${JSON.stringify(moduleId)}, fact: compiled${index}[${contribution}].contribution },`)
|
|
481
|
+
]);
|
|
482
|
+
return [
|
|
483
|
+
generatedHeader,
|
|
484
|
+
"import type { CrudFormSectionFactEntry, CrudFormSectionServerModule } from '@open-mercato/shared/modules/form-sections'",
|
|
485
|
+
...imports,
|
|
486
|
+
...hasGenericSinks ? ["import { ormEntityExportNamespaces } from './entities.generated'"] : [],
|
|
487
|
+
...compiledDeclarations.length ? [
|
|
488
|
+
"import { bindCompiledCrudFormAlternatives, bindCompiledCrudFormContributions, type CompiledCrudFormContribution } from '@open-mercato/shared/lib/crud/form-sections/compiled-extensions'"
|
|
489
|
+
] : [],
|
|
490
|
+
...compiledDeclarations.some((line) => line.includes(" as InjectionPosition")) ? [injectionPositionTypeImport] : [],
|
|
491
|
+
...modules.some(({ derivedRoutes }) => derivedRoutes.length) ? ["import { bindDerivedCrudRouteSectionHosts } from '@open-mercato/shared/lib/crud/form-sections/derived-route-host'"] : [],
|
|
492
|
+
"",
|
|
493
|
+
...hasGenericSinks ? [
|
|
494
|
+
"export { entities as crudFormSectionOrmEntities } from './entities.generated'",
|
|
495
|
+
"const lookupCompiledOrmExports = (moduleId: string) => ormEntityExportNamespaces.find((entry) => entry.moduleId === moduleId)?.entities"
|
|
496
|
+
] : [],
|
|
497
|
+
...compiledDeclarations,
|
|
498
|
+
"export const crudFormSectionFactEntries = [",
|
|
499
|
+
...entries,
|
|
500
|
+
"] as const satisfies readonly CrudFormSectionFactEntry[]",
|
|
501
|
+
"",
|
|
502
|
+
"export const crudFormSectionServerModules = [",
|
|
503
|
+
...modules.map(({ moduleId, derivedRoutes, hasHandwrittenSections }, index) => {
|
|
504
|
+
const alternatives = compiled.alternativesByModule.get(moduleId);
|
|
505
|
+
const bindings = derivedRoutes.map((route) => {
|
|
506
|
+
const retrySinks = [...new Set(alternatives?.flatMap((alternative) => alternative.hostDescriptorId === route.hostDescriptorId ? alternative.outboxRetrySinkIds ?? [] : []))].sort(compareIds);
|
|
507
|
+
return `{ declaration: sections${index}.derivedHosts[${route.index}], route: ${JSON.stringify(route.routePath)}, outboxRetrySinkIds: ${JSON.stringify(retrySinks)} }`;
|
|
508
|
+
});
|
|
509
|
+
const primitive = bindings.length ? `bindDerivedCrudRouteSectionHosts(sections${index}, [${bindings.join(", ")}])` : hasHandwrittenSections ? `sections${index}` : "{}";
|
|
510
|
+
const sections = compiled.contributionsByModule.has(moduleId) ? `bindCompiledCrudFormContributions(${primitive}, compiled${index}, compiledOverrides${index})` : primitive;
|
|
511
|
+
const entry = `{ moduleId: ${JSON.stringify(moduleId)}, sections: ${sections} }`;
|
|
512
|
+
return ` ${alternatives?.length ? `bindCompiledCrudFormAlternatives(${entry}, ${JSON.stringify(alternatives)})` : entry},`;
|
|
513
|
+
}),
|
|
514
|
+
"] as const satisfies readonly CrudFormSectionServerModule[]",
|
|
515
|
+
""
|
|
516
|
+
].join("\n");
|
|
517
|
+
}
|
|
518
|
+
function renderRuntimeRegistry(modules, compiled) {
|
|
519
|
+
const overrides = renderSectionOverrides(Object.assign({}, ...modules.map((module) => module.contributedOverrides), compiled.fallbacks));
|
|
520
|
+
const entries = modules.flatMap(({ moduleId, descriptors }) => [
|
|
521
|
+
...descriptors.map(
|
|
522
|
+
({ id, roundTripId, kind, runtimePath }) => ` { id: ${stringLiteral(id)}, roundTripId: ${stringLiteral(roundTripId)}, kind: ${stringLiteral(kind)}, moduleId: ${stringLiteral(moduleId)}, load: () => import(${stringLiteral(runtimePath)}) },`
|
|
523
|
+
),
|
|
524
|
+
...(compiled.contributionsByModule.get(moduleId) ?? []).map(({ contribution: { id, roundTripId }, file }) => ` { id: ${stringLiteral(id)}, roundTripId: ${stringLiteral(roundTripId)}, kind: "contribution", moduleId: ${stringLiteral(moduleId)}, load: () => import(${stringLiteral("./" + stripModuleCodeExtension(file))}) },`)
|
|
525
|
+
]);
|
|
526
|
+
const versionedSinks = [...compiled.contributionsByModule.values()].flatMap((entries2) => entries2.flatMap(({ contribution, sinks }) => sinks.flatMap(({ id, fields }) => {
|
|
527
|
+
const first = fields[0];
|
|
528
|
+
const kind = first.field.store?.kind;
|
|
529
|
+
const { hostId, formVariant, formOperation } = contribution.address;
|
|
530
|
+
return kind === "table" || kind === "external" ? [{
|
|
531
|
+
id,
|
|
532
|
+
hostId,
|
|
533
|
+
formVariant,
|
|
534
|
+
formOperation,
|
|
535
|
+
kind,
|
|
536
|
+
ownerModuleId: first.authored.module.moduleId,
|
|
537
|
+
payloadPaths: fields.map(({ payloadPath }) => payloadPath)
|
|
538
|
+
}] : [];
|
|
539
|
+
})));
|
|
540
|
+
return [
|
|
541
|
+
generatedHeader,
|
|
542
|
+
"import type { CrudFormSectionClientHostFact, CrudFormSectionRuntimeEntry } from '@open-mercato/shared/modules/form-sections'",
|
|
543
|
+
"import type { CrudFormSectionClientVersionedSink } from '@open-mercato/shared/lib/crud/form-sections/client-registry'",
|
|
544
|
+
"import type { FormSectionOverridesMap } from '@open-mercato/shared/modules/overrides'",
|
|
545
|
+
...overrides.includes(" as InjectionPosition") ? [injectionPositionTypeImport] : [],
|
|
546
|
+
"",
|
|
547
|
+
`export const crudFormSectionClientHostFacts = ${escapeGeneratedJsonLiteral(JSON.stringify(modules.flatMap((module) => module.clientHosts), null, 2))} as const satisfies readonly CrudFormSectionClientHostFact[]`,
|
|
548
|
+
`export const crudFormSectionClientVersionedSinks = ${escapeGeneratedJsonLiteral(JSON.stringify(versionedSinks))} as const satisfies readonly CrudFormSectionClientVersionedSink[]`,
|
|
549
|
+
`export const crudFormSectionContributedOverrides = ${overrides} as const satisfies Readonly<FormSectionOverridesMap>`,
|
|
550
|
+
"",
|
|
551
|
+
"export const crudFormSectionRuntimeEntries: readonly CrudFormSectionRuntimeEntry[] = [",
|
|
552
|
+
...entries,
|
|
553
|
+
"]",
|
|
554
|
+
"",
|
|
555
|
+
"const runtimesById = new Map(crudFormSectionRuntimeEntries.map((entry) => [entry.id, entry]))",
|
|
556
|
+
"",
|
|
557
|
+
"export function getCrudFormSectionRuntime(id: string): CrudFormSectionRuntimeEntry | undefined {",
|
|
558
|
+
" return runtimesById.get(id)",
|
|
559
|
+
"}",
|
|
560
|
+
""
|
|
561
|
+
].join("\n");
|
|
562
|
+
}
|
|
563
|
+
function prepareCrudFormSectionRegistries(options) {
|
|
564
|
+
const sections = /* @__PURE__ */ new Map();
|
|
565
|
+
for (const module of options.modules) {
|
|
566
|
+
const declaration = parseModuleSections(module, true);
|
|
567
|
+
if (declaration) sections.set(module.modId, declaration);
|
|
568
|
+
}
|
|
569
|
+
const modules = orderedSectionModules(sections, options.identities, options.requiresByModule);
|
|
570
|
+
const modulesById = /* @__PURE__ */ new Map();
|
|
571
|
+
const defaultModulesById = /* @__PURE__ */ new Map();
|
|
572
|
+
const sinkModulesById = /* @__PURE__ */ new Map();
|
|
573
|
+
for (const module of modules) {
|
|
574
|
+
for (const id of module.sinkIds) {
|
|
575
|
+
const owner = sinkModulesById.get(id);
|
|
576
|
+
if (owner) throw new Error(`[generate] Duplicate CrudForm section sink id "${id}" in "${owner}" and "${module.moduleId}"`);
|
|
577
|
+
sinkModulesById.set(id, module.moduleId);
|
|
578
|
+
}
|
|
579
|
+
for (const id of module.leafDefaultProviderIds) {
|
|
580
|
+
const owner = defaultModulesById.get(id);
|
|
581
|
+
if (owner) {
|
|
582
|
+
throw new Error(`[generate] Duplicate leaf default provider id "${id}" in "${owner}" and "${module.moduleId}"`);
|
|
583
|
+
}
|
|
584
|
+
defaultModulesById.set(id, module.moduleId);
|
|
585
|
+
}
|
|
586
|
+
for (const { id } of module.descriptors) {
|
|
587
|
+
const owner = modulesById.get(id);
|
|
588
|
+
if (owner) {
|
|
589
|
+
throw new Error(`[generate] Duplicate form-sections descriptor id "${id}" in "${owner}" and "${module.moduleId}"`);
|
|
590
|
+
}
|
|
591
|
+
modulesById.set(id, module.moduleId);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
const compiled = compileCrudFormSectionExtensions(modules, Object.assign({}, ...options.modules.map(({ formSectionOverrides }) => formSectionOverrides)));
|
|
595
|
+
for (const [moduleId, candidates] of compiled.contributionsByModule) for (const { id } of candidates) {
|
|
596
|
+
const owner = modulesById.get(id);
|
|
597
|
+
if (owner) throw new Error(`[generate] Duplicate form-sections descriptor id "${id}" in "${owner}" and "${moduleId}"`);
|
|
598
|
+
modulesById.set(id, moduleId);
|
|
599
|
+
}
|
|
600
|
+
return { modules, compiled };
|
|
601
|
+
}
|
|
602
|
+
function projectCrudFormSectionContributions({ modules, compiled }) {
|
|
603
|
+
return new Map(modules.map((module) => {
|
|
604
|
+
const rows = [];
|
|
605
|
+
for (const { id, address, operation } of module.primitiveContributions) {
|
|
606
|
+
rows.push({
|
|
607
|
+
id,
|
|
608
|
+
key: crudFormSectionOverrideKey(address),
|
|
609
|
+
operation,
|
|
610
|
+
sourceFileName: module.sourceFileName,
|
|
611
|
+
exportName: "crudFormSections"
|
|
612
|
+
});
|
|
613
|
+
}
|
|
614
|
+
for (const { contribution: { id, address, operation } } of compiled.contributionsByModule.get(module.moduleId) ?? []) {
|
|
615
|
+
rows.push({
|
|
616
|
+
id,
|
|
617
|
+
key: crudFormSectionOverrideKey(address),
|
|
618
|
+
operation,
|
|
619
|
+
sourceFileName: module.sourceFileName,
|
|
620
|
+
exportName: "crudFormExtensions"
|
|
621
|
+
});
|
|
622
|
+
}
|
|
623
|
+
return [module.moduleId, rows.sort((left, right) => compareIds(left.id, right.id))];
|
|
624
|
+
}));
|
|
625
|
+
}
|
|
626
|
+
function writeCrudFormSectionRegistries(options) {
|
|
627
|
+
const { modules, compiled } = options.prepared ?? prepareCrudFormSectionRegistries(options);
|
|
628
|
+
const revisions = [...modules.flatMap(({ revisionWrite }) => revisionWrite ? [revisionWrite] : []), ...compiled.revisionWrites];
|
|
629
|
+
for (const revisionWrite of revisions) {
|
|
630
|
+
const temporary = `${revisionWrite.filename}.${randomUUID()}.tmp`;
|
|
631
|
+
try {
|
|
632
|
+
fs.writeFileSync(temporary, revisionWrite.content, { flag: "wx" });
|
|
633
|
+
fs.renameSync(temporary, revisionWrite.filename);
|
|
634
|
+
} finally {
|
|
635
|
+
fs.rmSync(temporary, { force: true });
|
|
636
|
+
}
|
|
637
|
+
options.result.filesWritten.push(revisionWrite.filename);
|
|
638
|
+
}
|
|
639
|
+
const outputs = [
|
|
640
|
+
["crud-form-section-facts", renderFactRegistry(modules, compiled)],
|
|
641
|
+
["crud-form-section-runtime", renderRuntimeRegistry(modules, compiled)],
|
|
642
|
+
...compiled.runtimeFiles.map(({ name, content }) => [name.slice(0, -".generated.ts".length), content])
|
|
643
|
+
];
|
|
644
|
+
const retainedRuntimeFiles = new Set(compiled.runtimeFiles.map(({ name }) => name));
|
|
645
|
+
if (fs.existsSync(options.outputDir)) for (const filename of fs.readdirSync(options.outputDir)) {
|
|
646
|
+
if (!/^crud-form-section-extension-[0-9a-f]{20}\.generated\.(?:checksum|ts)$/.test(filename) || retainedRuntimeFiles.has(filename.replace(/\.checksum$/, ".ts"))) continue;
|
|
647
|
+
fs.rmSync(path.join(options.outputDir, filename), { force: true });
|
|
648
|
+
}
|
|
649
|
+
if (!options.quiet) for (const [moduleId, candidates] of compiled.contributionsByModule) {
|
|
650
|
+
for (const candidate of candidates) {
|
|
651
|
+
const owned = candidate.ownership?.payloadPaths.join(", ") || "none";
|
|
652
|
+
const stores = candidate.fields.filter(({ field }) => field.store).map(({ field }) => `${field.id}/${field.store.kind}`).join(", ") || "none";
|
|
653
|
+
console.log(`[generate] CrudForm extension ${moduleId}/${candidate.id} ${candidate.override.operation}; fields: ${candidate.fields.length}, payload leaves: ${owned}, defaults: ${candidate.defaults.length}, stores: ${stores}, field rules: ${candidate.fields.filter(({ field }) => field.server || field.rules.length).length}`);
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
for (const [name, content] of outputs) {
|
|
657
|
+
writeGeneratedFile({
|
|
658
|
+
outFile: path.join(options.outputDir, `${name}.generated.ts`),
|
|
659
|
+
checksumFile: path.join(options.outputDir, `${name}.generated.checksum`),
|
|
660
|
+
content,
|
|
661
|
+
structureChecksum: options.structureChecksum,
|
|
662
|
+
result: options.result,
|
|
663
|
+
quiet: options.quiet
|
|
664
|
+
});
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
const derivedRouteFilePattern = /^crud-form-section-route-[a-f0-9]{16}\.generated\.ts$/;
|
|
668
|
+
function writeDerivedCrudFormSectionRoutes(options) {
|
|
669
|
+
const routes = /* @__PURE__ */ new Map();
|
|
670
|
+
for (const module of options.modules) {
|
|
671
|
+
const source = parseModuleSections(module);
|
|
672
|
+
if (!source) continue;
|
|
673
|
+
const hostIds = new Set(source.descriptors.filter(({ kind }) => kind === "host").map(({ id }) => id));
|
|
674
|
+
const bound = /* @__PURE__ */ new Set();
|
|
675
|
+
for (const entry of source.derivedRoutes) {
|
|
676
|
+
if (!hostIds.has(entry.hostDescriptorId) || bound.has(entry.hostDescriptorId)) {
|
|
677
|
+
throw new Error(`[generate] Derived CrudForm route requires one matching host fact in "${module.modId}"`);
|
|
678
|
+
}
|
|
679
|
+
bound.add(entry.hostDescriptorId);
|
|
680
|
+
const existing = routes.get(entry.routePath);
|
|
681
|
+
if (existing && existing.moduleId !== module.modId) {
|
|
682
|
+
throw new Error(`[generate] Duplicate derived CrudForm route "${entry.routePath}"`);
|
|
683
|
+
}
|
|
684
|
+
const route = existing ?? { moduleId: module.modId, importPath: source.importPath, entries: [] };
|
|
685
|
+
route.entries.push(entry);
|
|
686
|
+
routes.set(entry.routePath, route);
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
const generated = [];
|
|
690
|
+
function emit(routePath, moduleId, methods, content) {
|
|
691
|
+
if (generated.some((route) => route.routePath === routePath)) {
|
|
692
|
+
throw new Error(`[generate] Duplicate derived CrudForm route "${routePath}"`);
|
|
693
|
+
}
|
|
694
|
+
const suffix = createHash("sha256").update(`${moduleId}:${routePath}`).digest("hex").slice(0, 16);
|
|
695
|
+
const fileName = `crud-form-section-route-${suffix}.generated.ts`;
|
|
696
|
+
generated.push({ moduleId, routePath, fileName, methods });
|
|
697
|
+
writeGeneratedFile({
|
|
698
|
+
outFile: path.join(options.outputDir, fileName),
|
|
699
|
+
checksumFile: path.join(options.outputDir, fileName.replace(/\.ts$/, ".checksum")),
|
|
700
|
+
content,
|
|
701
|
+
structureChecksum: options.structureChecksum,
|
|
702
|
+
result: options.result,
|
|
703
|
+
quiet: options.quiet
|
|
704
|
+
});
|
|
705
|
+
}
|
|
706
|
+
for (const [routePath, { moduleId, importPath, entries }] of [...routes].sort(([left], [right]) => compareIds(left, right))) {
|
|
707
|
+
const methods = [...new Set(entries.flatMap(({ operations }) => operations.map((operation) => derivedRouteMethods[operation])))].sort(compareIds);
|
|
708
|
+
const routeImport = `import { crudFormSections } from ${JSON.stringify(importPath)}`;
|
|
709
|
+
const declarations = (binding) => `[${binding.map(({ index }) => `crudFormSections.derivedHosts[${index}]`).join(", ")}]`;
|
|
710
|
+
const content = [
|
|
711
|
+
generatedHeader,
|
|
712
|
+
"import { createDerivedCrudFormSectionFacade } from '@open-mercato/shared/lib/crud/form-sections/derived-route-host'",
|
|
713
|
+
routeImport,
|
|
714
|
+
`const facade = createDerivedCrudFormSectionFacade(${declarations(entries)}, ${JSON.stringify(routePath)}, ${JSON.stringify(methods)})`,
|
|
715
|
+
"export const metadata = facade.metadata",
|
|
716
|
+
"export const openApi = facade.openApi",
|
|
717
|
+
...methods.map((method) => `export const ${method} = facade.handlers.${method}!`),
|
|
718
|
+
""
|
|
719
|
+
].join("\n");
|
|
720
|
+
emit(routePath, moduleId, methods, content);
|
|
721
|
+
const retry = entries.filter(({ outboxRetry }) => outboxRetry);
|
|
722
|
+
if (retry.length) {
|
|
723
|
+
emit(derivedCrudFormSectionRetryPath(routePath), moduleId, ["POST"], [
|
|
724
|
+
generatedHeader,
|
|
725
|
+
"import { createDerivedCrudFormSectionOutboxRetryRoute } from '@open-mercato/shared/lib/crud/form-sections/derived-route-host'",
|
|
726
|
+
routeImport,
|
|
727
|
+
`export const { metadata, openApi, POST } = createDerivedCrudFormSectionOutboxRetryRoute(${declarations(retry)}, ${JSON.stringify(routePath)})`,
|
|
728
|
+
""
|
|
729
|
+
].join("\n"));
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
const indexPath = path.join(options.outputDir, generatedDerivedCrudRouteIndex);
|
|
733
|
+
if (generated.length || fs.existsSync(indexPath)) {
|
|
734
|
+
writeGeneratedFile({
|
|
735
|
+
outFile: indexPath,
|
|
736
|
+
checksumFile: indexPath.replace(/\.json$/, ".checksum"),
|
|
737
|
+
content: JSON.stringify(generated, null, 2) + "\n",
|
|
738
|
+
structureChecksum: options.structureChecksum,
|
|
739
|
+
result: options.result,
|
|
740
|
+
quiet: options.quiet
|
|
741
|
+
});
|
|
742
|
+
}
|
|
743
|
+
const current = new Set(generated.map(({ fileName }) => fileName));
|
|
744
|
+
if (fs.existsSync(options.outputDir)) {
|
|
745
|
+
for (const fileName of fs.readdirSync(options.outputDir)) {
|
|
746
|
+
if (!derivedRouteFilePattern.test(fileName) || current.has(fileName)) continue;
|
|
747
|
+
fs.rmSync(path.join(options.outputDir, fileName), { force: true });
|
|
748
|
+
fs.rmSync(path.join(options.outputDir, fileName.replace(/\.ts$/, ".checksum")), { force: true });
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
return generated;
|
|
752
|
+
}
|
|
753
|
+
function readDerivedCrudFormSectionRouteIndex(outputDir) {
|
|
754
|
+
const filePath = path.join(outputDir, generatedDerivedCrudRouteIndex);
|
|
755
|
+
if (!fs.existsSync(filePath)) return [];
|
|
756
|
+
const entries = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
|
757
|
+
if (!Array.isArray(entries)) throw new Error("[generate] Invalid generated derived route index");
|
|
758
|
+
return entries.map((entry) => {
|
|
759
|
+
if (typeof entry.moduleId !== "string" || typeof entry.routePath !== "string" || !/\/section-policy(?:\/retry)?$/.test(entry.routePath) || typeof entry.fileName !== "string" || !derivedRouteFilePattern.test(entry.fileName) || !Array.isArray(entry.methods) || !entry.methods.every((method) => ["POST", "PUT", "DELETE"].includes(method))) {
|
|
760
|
+
throw new Error("[generate] Invalid derived route index entry");
|
|
761
|
+
}
|
|
762
|
+
return { moduleId: entry.moduleId, routePath: entry.routePath, fileName: entry.fileName, methods: entry.methods };
|
|
763
|
+
});
|
|
764
|
+
}
|
|
765
|
+
export {
|
|
766
|
+
generatedDerivedCrudRouteIndex,
|
|
767
|
+
prepareCrudFormSectionRegistries,
|
|
768
|
+
projectCrudFormSectionContributions,
|
|
769
|
+
readDerivedCrudFormSectionRouteIndex,
|
|
770
|
+
writeCrudFormSectionRegistries,
|
|
771
|
+
writeDerivedCrudFormSectionRoutes
|
|
772
|
+
};
|
|
773
|
+
//# sourceMappingURL=form-sections.js.map
|