@contractspec/module.examples 1.57.0 → 1.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,914 @@
1
- import { EXAMPLE_REGISTRY, ExampleRegistry, getExample, listExamples, searchExamples } from "./registry.js";
2
- import { createTemplateTransformEngine, getTemplateEngine, resetTemplateEngine } from "./runtime/engine.js";
3
- import { TEMPLATE_REGISTRY, getClonableTemplates, getTemplate, getTemplatesByModule, listTemplates } from "./runtime/registry.js";
4
- import { TemplateInstaller } from "./runtime/installer.js";
5
- import { TemplateHandlers, TemplateRuntimeProvider, useAgentHandlers, useAnalyticsHandlers, useCrmHandlers, useIntegrationHandlers, useMarketplaceHandlers, useSaasHandlers, useTemplateEngine, useTemplateHandlers, useWorkflowHandlers } from "./runtime/context.js";
1
+ // @bun
2
+ // src/registry.ts
3
+ import { ExampleRegistry } from "@contractspec/lib.contracts";
6
4
 
7
- export { EXAMPLE_REGISTRY, ExampleRegistry, TEMPLATE_REGISTRY, TemplateHandlers, TemplateInstaller, TemplateRuntimeProvider, createTemplateTransformEngine, getClonableTemplates, getExample, getTemplate, getTemplateEngine, getTemplatesByModule, listExamples, listTemplates, resetTemplateEngine, searchExamples, useAgentHandlers, useAnalyticsHandlers, useCrmHandlers, useIntegrationHandlers, useMarketplaceHandlers, useSaasHandlers, useTemplateEngine, useTemplateHandlers, useWorkflowHandlers };
5
+ // src/builtins.ts
6
+ import AgentConsole from "@contractspec/example.agent-console/example";
7
+ import AiSupportBot from "@contractspec/example.ai-support-bot/example";
8
+ import AnalyticsDashboard from "@contractspec/example.analytics-dashboard/example";
9
+ import ContentGeneration from "@contractspec/example.content-generation/example";
10
+ import CrmPipeline from "@contractspec/example.crm-pipeline/example";
11
+ import IntegrationHub from "@contractspec/example.integration-hub/example";
12
+ import IntegrationStripe from "@contractspec/example.integration-stripe/example";
13
+ import VoiceProviders from "@contractspec/example.voice-providers/example";
14
+ import KbUpdatePipeline from "@contractspec/example.kb-update-pipeline/example";
15
+ import KnowledgeCanon from "@contractspec/example.knowledge-canon/example";
16
+ import LearningPatterns from "@contractspec/example.learning-patterns/example";
17
+ import LearningJourneyAmbientCoach from "@contractspec/example.learning-journey-ambient-coach/example";
18
+ import LearningJourneyCrmOnboarding from "@contractspec/example.learning-journey-crm-onboarding/example";
19
+ import LearningJourneyDuoDrills from "@contractspec/example.learning-journey-duo-drills/example";
20
+ import LearningJourneyPlatformTour from "@contractspec/example.learning-journey-platform-tour/example";
21
+ import LearningJourneyQuestChallenges from "@contractspec/example.learning-journey-quest-challenges/example";
22
+ import LearningJourneyRegistry from "@contractspec/example.learning-journey-registry/example";
23
+ import LearningJourneyStudioOnboarding from "@contractspec/example.learning-journey-studio-onboarding/example";
24
+ import LearningJourneyUiCoaching from "@contractspec/example.learning-journey-ui-coaching/example";
25
+ import LearningJourneyUiGamified from "@contractspec/example.learning-journey-ui-gamified/example";
26
+ import LearningJourneyUiOnboarding from "@contractspec/example.learning-journey-ui-onboarding/example";
27
+ import LearningJourneyUiShared from "@contractspec/example.learning-journey-ui-shared/example";
28
+ import LifecycleCli from "@contractspec/example.lifecycle-cli/example";
29
+ import LifecycleDashboard from "@contractspec/example.lifecycle-dashboard/example";
30
+ import LocaleJurisdictionGate from "@contractspec/example.locale-jurisdiction-gate/example";
31
+ import Marketplace from "@contractspec/example.marketplace/example";
32
+ import OpenbankingPowens from "@contractspec/example.openbanking-powens/example";
33
+ import Personalization from "@contractspec/example.personalization/example";
34
+ import PolicySafeKnowledgeAssistant from "@contractspec/example.policy-safe-knowledge-assistant/example";
35
+ import SaasBoilerplate from "@contractspec/example.saas-boilerplate/example";
36
+ import ServiceBusinessOs from "@contractspec/example.service-business-os/example";
37
+ import TeamHub from "@contractspec/example.team-hub/example";
38
+ import VersionedKnowledgeBase from "@contractspec/example.versioned-knowledge-base/example";
39
+ import WealthSnapshot from "@contractspec/example.wealth-snapshot/example";
40
+ import WorkflowSystem from "@contractspec/example.workflow-system/example";
41
+ var EXAMPLE_REGISTRY = [
42
+ AgentConsole,
43
+ AiSupportBot,
44
+ AnalyticsDashboard,
45
+ ContentGeneration,
46
+ CrmPipeline,
47
+ IntegrationHub,
48
+ IntegrationStripe,
49
+ VoiceProviders,
50
+ KbUpdatePipeline,
51
+ KnowledgeCanon,
52
+ LearningPatterns,
53
+ LearningJourneyAmbientCoach,
54
+ LearningJourneyCrmOnboarding,
55
+ LearningJourneyDuoDrills,
56
+ LearningJourneyPlatformTour,
57
+ LearningJourneyQuestChallenges,
58
+ LearningJourneyRegistry,
59
+ LearningJourneyStudioOnboarding,
60
+ LearningJourneyUiCoaching,
61
+ LearningJourneyUiGamified,
62
+ LearningJourneyUiOnboarding,
63
+ LearningJourneyUiShared,
64
+ LifecycleCli,
65
+ LifecycleDashboard,
66
+ LocaleJurisdictionGate,
67
+ Marketplace,
68
+ OpenbankingPowens,
69
+ Personalization,
70
+ PolicySafeKnowledgeAssistant,
71
+ SaasBoilerplate,
72
+ ServiceBusinessOs,
73
+ TeamHub,
74
+ VersionedKnowledgeBase,
75
+ WealthSnapshot,
76
+ WorkflowSystem
77
+ ];
78
+
79
+ // src/registry.ts
80
+ import { ExampleRegistry as ExampleRegistry2 } from "@contractspec/lib.contracts";
81
+ var globalRegistry = new ExampleRegistry;
82
+ for (const example of EXAMPLE_REGISTRY) {
83
+ globalRegistry.register(example);
84
+ }
85
+ var EXAMPLE_REGISTRY2 = globalRegistry.list();
86
+ function listExamples() {
87
+ return globalRegistry.list();
88
+ }
89
+ function getExample(key) {
90
+ return globalRegistry.get(key);
91
+ }
92
+ function searchExamples(query) {
93
+ return globalRegistry.search(query);
94
+ }
95
+ // src/runtime/engine.ts
96
+ import {
97
+ createDefaultTransformEngine,
98
+ registerBasicValidation,
99
+ registerDefaultReactRenderer
100
+ } from "@contractspec/lib.contracts/presentations";
101
+ import {
102
+ agentDashboardMarkdownRenderer,
103
+ agentListMarkdownRenderer,
104
+ agentListReactRenderer,
105
+ runListMarkdownRenderer,
106
+ toolRegistryMarkdownRenderer
107
+ } from "@contractspec/example.agent-console";
108
+ import {
109
+ projectListMarkdownRenderer,
110
+ projectListReactRenderer,
111
+ saasBillingMarkdownRenderer,
112
+ saasDashboardMarkdownRenderer
113
+ } from "@contractspec/example.saas-boilerplate";
114
+ import {
115
+ crmDashboardMarkdownRenderer,
116
+ crmPipelineMarkdownRenderer,
117
+ crmPipelineReactRenderer
118
+ } from "@contractspec/example.crm-pipeline";
119
+ import {
120
+ workflowDashboardMarkdownRenderer,
121
+ workflowDefinitionListMarkdownRenderer,
122
+ workflowInstanceDetailMarkdownRenderer
123
+ } from "@contractspec/example.workflow-system";
124
+ import {
125
+ marketplaceDashboardMarkdownRenderer,
126
+ orderListMarkdownRenderer,
127
+ productCatalogMarkdownRenderer
128
+ } from "@contractspec/example.marketplace";
129
+ import {
130
+ connectionListMarkdownRenderer,
131
+ integrationDashboardMarkdownRenderer,
132
+ syncConfigMarkdownRenderer
133
+ } from "@contractspec/example.integration-hub";
134
+ import {
135
+ analyticsDashboardMarkdownRenderer,
136
+ dashboardListMarkdownRenderer,
137
+ queryBuilderMarkdownRenderer
138
+ } from "@contractspec/example.analytics-dashboard";
139
+ function createTemplateTransformEngine() {
140
+ const engine = createDefaultTransformEngine();
141
+ registerDefaultReactRenderer(engine);
142
+ registerBasicValidation(engine);
143
+ registerTemplateRenderers(engine);
144
+ return engine;
145
+ }
146
+ function registerTemplateRenderers(engine) {
147
+ engine.register(agentListReactRenderer);
148
+ engine.register(agentListMarkdownRenderer);
149
+ engine.register(runListMarkdownRenderer);
150
+ engine.register(toolRegistryMarkdownRenderer);
151
+ engine.register(agentDashboardMarkdownRenderer);
152
+ engine.register(projectListReactRenderer);
153
+ engine.register(projectListMarkdownRenderer);
154
+ engine.register(saasDashboardMarkdownRenderer);
155
+ engine.register(saasBillingMarkdownRenderer);
156
+ engine.register(crmPipelineReactRenderer);
157
+ engine.register(crmPipelineMarkdownRenderer);
158
+ engine.register(crmDashboardMarkdownRenderer);
159
+ engine.register(workflowDashboardMarkdownRenderer);
160
+ engine.register(workflowDefinitionListMarkdownRenderer);
161
+ engine.register(workflowInstanceDetailMarkdownRenderer);
162
+ engine.register(marketplaceDashboardMarkdownRenderer);
163
+ engine.register(productCatalogMarkdownRenderer);
164
+ engine.register(orderListMarkdownRenderer);
165
+ engine.register(integrationDashboardMarkdownRenderer);
166
+ engine.register(connectionListMarkdownRenderer);
167
+ engine.register(syncConfigMarkdownRenderer);
168
+ engine.register(analyticsDashboardMarkdownRenderer);
169
+ engine.register(dashboardListMarkdownRenderer);
170
+ engine.register(queryBuilderMarkdownRenderer);
171
+ }
172
+ var templateEngine = null;
173
+ function getTemplateEngine() {
174
+ if (!templateEngine) {
175
+ templateEngine = createTemplateTransformEngine();
176
+ }
177
+ return templateEngine;
178
+ }
179
+ function resetTemplateEngine() {
180
+ templateEngine = null;
181
+ }
182
+ // src/runtime/registry.ts
183
+ var PRESENTATIONS_BY_TEMPLATE = {
184
+ "saas-boilerplate": [
185
+ "saas-boilerplate.dashboard",
186
+ "saas-boilerplate.project.list",
187
+ "saas-boilerplate.billing.settings"
188
+ ],
189
+ "crm-pipeline": ["crm-pipeline.dashboard", "crm-pipeline.deal.pipeline"],
190
+ "agent-console": [
191
+ "agent-console.dashboard",
192
+ "agent-console.agent.list",
193
+ "agent-console.run.list",
194
+ "agent-console.tool.registry"
195
+ ],
196
+ "workflow-system": [
197
+ "workflow-system.dashboard",
198
+ "workflow-system.definition.list",
199
+ "workflow-system.instance.detail"
200
+ ],
201
+ marketplace: [
202
+ "marketplace.dashboard",
203
+ "marketplace.product.catalog",
204
+ "marketplace.order.list",
205
+ "marketplace.store.manage"
206
+ ],
207
+ "integration-hub": [
208
+ "integration-hub.dashboard",
209
+ "integration-hub.connection.list",
210
+ "integration-hub.sync.config"
211
+ ],
212
+ "analytics-dashboard": [
213
+ "analytics-dashboard.dashboard",
214
+ "analytics-dashboard.list",
215
+ "analytics-dashboard.query.builder"
216
+ ],
217
+ "learning-journey-studio-onboarding": [
218
+ "learning.journey.track_list",
219
+ "learning.journey.track_detail",
220
+ "learning.journey.progress_widget"
221
+ ],
222
+ "learning-journey-platform-tour": [
223
+ "learning.journey.track_list",
224
+ "learning.journey.track_detail",
225
+ "learning.journey.progress_widget"
226
+ ],
227
+ "learning-journey-crm-onboarding": [
228
+ "learning.journey.track_list",
229
+ "learning.journey.track_detail",
230
+ "learning.journey.progress_widget"
231
+ ],
232
+ "learning-journey-duo-drills": [
233
+ "learning.journey.track_list",
234
+ "learning.journey.track_detail",
235
+ "learning.journey.progress_widget"
236
+ ],
237
+ "learning-journey-ambient-coach": [
238
+ "learning.journey.track_list",
239
+ "learning.journey.track_detail",
240
+ "learning.journey.progress_widget"
241
+ ],
242
+ "learning-journey-quest-challenges": [
243
+ "learning.journey.track_list",
244
+ "learning.journey.track_detail",
245
+ "learning.journey.progress_widget"
246
+ ]
247
+ };
248
+ var TEMPLATE_REGISTRY = [
249
+ {
250
+ id: "todos-app",
251
+ name: "To-dos List App",
252
+ description: "CRUD flows, filtering, priorities, and ceremonies for handing off work across crews.",
253
+ category: "productivity",
254
+ complexity: "beginner",
255
+ icon: "\u2705",
256
+ features: ["CRUD tasks", "Filters", "Categories", "Search", "Priorities"],
257
+ tags: ["tasks", "ops", "starter"],
258
+ schema: {
259
+ models: ["Task", "TaskCategory"],
260
+ contracts: ["template.todos.crud"]
261
+ },
262
+ components: {
263
+ list: "TaskList",
264
+ detail: "TaskDetailPanel",
265
+ form: "TaskForm"
266
+ },
267
+ preview: {
268
+ demoUrl: "/sandbox?template=todos-app"
269
+ },
270
+ docs: {
271
+ quickstart: "/docs/templates/todos-app"
272
+ }
273
+ },
274
+ {
275
+ id: "messaging-app",
276
+ name: "Messaging Application",
277
+ description: "Conversation roster, optimistic sending, typing indicators, and delivery telemetry.",
278
+ category: "communication",
279
+ complexity: "intermediate",
280
+ icon: "\uD83D\uDCAC",
281
+ features: [
282
+ "Conversations",
283
+ "Real-time feed",
284
+ "Typing indicators",
285
+ "Read receipts"
286
+ ],
287
+ tags: ["messaging", "realtime", "ws"],
288
+ schema: {
289
+ models: ["Conversation", "ConversationParticipant", "Message"],
290
+ contracts: ["template.messaging.core"]
291
+ },
292
+ components: {
293
+ list: "ConversationList",
294
+ detail: "MessageThread",
295
+ form: "MessageComposer"
296
+ },
297
+ preview: {
298
+ demoUrl: "/sandbox?template=messaging-app"
299
+ },
300
+ docs: {
301
+ quickstart: "/docs/templates/messaging-app"
302
+ }
303
+ },
304
+ {
305
+ id: "recipe-app-i18n",
306
+ name: "Recipe App (i18n)",
307
+ description: "Localized browsing experience with bilingual content, categories, and favorites.",
308
+ category: "content",
309
+ complexity: "intermediate",
310
+ icon: "\uD83C\uDF72",
311
+ features: ["i18n", "Favorites", "Categories", "Search", "RTL-ready"],
312
+ tags: ["content", "i18n", "localization"],
313
+ schema: {
314
+ models: [
315
+ "RecipeCategory",
316
+ "Recipe",
317
+ "RecipeIngredient",
318
+ "RecipeInstruction"
319
+ ],
320
+ contracts: ["template.recipes.browse"]
321
+ },
322
+ components: {
323
+ list: "RecipeList",
324
+ detail: "RecipeDetail",
325
+ form: "RecipeForm"
326
+ },
327
+ preview: {
328
+ demoUrl: "/sandbox?template=recipe-app-i18n"
329
+ },
330
+ docs: {
331
+ quickstart: "/docs/templates/recipe-app-i18n"
332
+ }
333
+ },
334
+ ...listExamples().map((example) => {
335
+ const tags = example.meta.keywords ?? [];
336
+ const category = tags.some((t) => t.toLowerCase() === "ai") || tags.some((t) => t.toLowerCase() === "assistant") ? "ai" : "business";
337
+ const complexity = "beginner";
338
+ const icon = "\uD83D\uDCE6";
339
+ return {
340
+ id: example.meta.key,
341
+ name: example.meta.title ?? example.meta.key,
342
+ description: example.meta.description ?? "",
343
+ category,
344
+ complexity,
345
+ icon,
346
+ features: [],
347
+ tags: [...tags],
348
+ schema: { models: [], contracts: [] },
349
+ components: { list: "ExampleList", detail: "ExampleDetail" },
350
+ preview: {
351
+ demoUrl: `/sandbox?template=${encodeURIComponent(example.meta.key)}`
352
+ },
353
+ package: example.entrypoints.packageName,
354
+ presentations: PRESENTATIONS_BY_TEMPLATE[example.meta.key] ?? [],
355
+ renderTargets: ["react", "markdown"]
356
+ };
357
+ })
358
+ ];
359
+ function listTemplates(filter) {
360
+ if (!filter)
361
+ return TEMPLATE_REGISTRY;
362
+ return TEMPLATE_REGISTRY.filter((template) => {
363
+ if (filter.category && template.category !== filter.category) {
364
+ return false;
365
+ }
366
+ if (filter.complexity && template.complexity !== filter.complexity) {
367
+ return false;
368
+ }
369
+ if (filter.tag && !template.tags.some((tag) => tag.toLowerCase() === filter.tag?.toLowerCase())) {
370
+ return false;
371
+ }
372
+ return true;
373
+ });
374
+ }
375
+ function getTemplate(id) {
376
+ return TEMPLATE_REGISTRY.find((template) => template.id === id);
377
+ }
378
+ function getTemplatesByModule(modulePackage) {
379
+ return TEMPLATE_REGISTRY.filter((template) => template.usesModules?.includes(modulePackage));
380
+ }
381
+ function getClonableTemplates() {
382
+ return TEMPLATE_REGISTRY.filter((template) => !!template.package);
383
+ }
384
+
385
+ // src/runtime/registry-client.ts
386
+ class ContractSpecRegistryClient {
387
+ baseUrl;
388
+ fetchImpl;
389
+ constructor(options) {
390
+ this.baseUrl = options.registryUrl.replace(/\/+$/, "");
391
+ this.fetchImpl = options.fetchImpl ?? fetch;
392
+ }
393
+ async getManifest() {
394
+ const res = await this.fetchImpl(`${this.baseUrl}/r/contractspec.json`, {
395
+ method: "GET",
396
+ headers: { Accept: "application/json" }
397
+ });
398
+ if (!res.ok) {
399
+ throw new Error(`Registry manifest fetch failed: ${res.status} ${res.statusText}`);
400
+ }
401
+ return await res.json();
402
+ }
403
+ async listByType(type) {
404
+ const manifest = await this.getManifest();
405
+ return manifest.items.filter((i) => i.type === type);
406
+ }
407
+ async listTemplateSummaries() {
408
+ const templates = await this.listByType("contractspec:template");
409
+ return templates.map((t) => ({
410
+ id: t.key,
411
+ title: t.title,
412
+ description: t.description,
413
+ version: t.version,
414
+ tags: t.meta.tags,
415
+ source: "registry"
416
+ }));
417
+ }
418
+ async getItem(typeSegment, name) {
419
+ const res = await this.fetchImpl(`${this.baseUrl}/r/contractspec/${typeSegment}/${name}.json`, {
420
+ method: "GET",
421
+ headers: { Accept: "application/json" }
422
+ });
423
+ if (!res.ok) {
424
+ throw new Error(`Registry item fetch failed: ${res.status} ${res.statusText}`);
425
+ }
426
+ return await res.json();
427
+ }
428
+ }
429
+
430
+ // src/runtime/installer.ts
431
+ import { web } from "@contractspec/lib.runtime-sandbox";
432
+ "use client";
433
+ var { LocalRuntimeServices } = web;
434
+ var SAVE_TEMPLATE_MUTATION = `
435
+ mutation SaveTemplateToStudio($input: SaveTemplateInput!) {
436
+ saveTemplateToStudio(input: $input) {
437
+ projectId
438
+ status
439
+ }
440
+ }
441
+ `;
442
+
443
+ class TemplateInstaller {
444
+ runtime;
445
+ endpoint;
446
+ registryUrl;
447
+ fetchImpl;
448
+ constructor(options = {}) {
449
+ this.runtime = options.runtime ?? new LocalRuntimeServices;
450
+ this.endpoint = options.endpoint ?? "/api/graphql";
451
+ this.registryUrl = options.registryUrl ? options.registryUrl.replace(/\/+$/, "") : null;
452
+ this.fetchImpl = options.fetchImpl ?? fetch;
453
+ }
454
+ async init() {
455
+ await this.runtime.init();
456
+ }
457
+ list(filter) {
458
+ return filter ? TEMPLATE_REGISTRY.filter((template) => {
459
+ if (filter.category && filter.category !== template.category) {
460
+ return false;
461
+ }
462
+ if (filter.complexity && filter.complexity !== template.complexity) {
463
+ return false;
464
+ }
465
+ if (filter.tag && !template.tags.includes(filter.tag)) {
466
+ return false;
467
+ }
468
+ return true;
469
+ }) : TEMPLATE_REGISTRY;
470
+ }
471
+ async listRemoteTemplates() {
472
+ if (!this.registryUrl)
473
+ return [];
474
+ const client = new ContractSpecRegistryClient({
475
+ registryUrl: this.registryUrl,
476
+ fetchImpl: this.fetchImpl
477
+ });
478
+ return await client.listTemplateSummaries();
479
+ }
480
+ resolveLocalTemplateId(id) {
481
+ const found = getTemplate(id);
482
+ return found ? id : null;
483
+ }
484
+ get(templateId) {
485
+ return getTemplate(templateId);
486
+ }
487
+ async install(templateId, options = {}) {
488
+ await this.runtime.seedTemplate({
489
+ templateId,
490
+ projectId: options.projectId
491
+ });
492
+ }
493
+ async saveToStudio(options) {
494
+ const snapshot = await this.runtime.db.export();
495
+ const payload = toBase64(snapshot);
496
+ const response = await this.fetchImpl(options.endpoint ?? this.endpoint, {
497
+ method: "POST",
498
+ headers: {
499
+ "Content-Type": "application/json",
500
+ ...options.token ? { Authorization: `Bearer ${options.token}` } : {}
501
+ },
502
+ body: JSON.stringify({
503
+ query: SAVE_TEMPLATE_MUTATION,
504
+ variables: {
505
+ input: {
506
+ templateId: options.templateId,
507
+ projectName: options.projectName,
508
+ organizationId: options.organizationId,
509
+ payload
510
+ }
511
+ }
512
+ })
513
+ });
514
+ if (!response.ok) {
515
+ throw new Error(`Failed to save template: ${response.status} ${response.statusText}`);
516
+ }
517
+ const json = await response.json();
518
+ if (json.errors?.length) {
519
+ throw new Error(json.errors[0]?.message ?? "Unknown error");
520
+ }
521
+ if (!json.data?.saveTemplateToStudio) {
522
+ throw new Error("Invalid response from Studio API");
523
+ }
524
+ return json.data.saveTemplateToStudio;
525
+ }
526
+ }
527
+ function toBase64(bytes) {
528
+ if (typeof Buffer !== "undefined") {
529
+ return Buffer.from(bytes).toString("base64");
530
+ }
531
+ let binary = "";
532
+ bytes.forEach((value) => {
533
+ binary += String.fromCharCode(value);
534
+ });
535
+ return btoa(binary);
536
+ }
537
+ // src/runtime/context.tsx
538
+ import { useEffect, useMemo, useState } from "react";
539
+ import { ApolloProvider } from "@apollo/client/react";
540
+ import { web as web2 } from "@contractspec/lib.runtime-sandbox";
541
+ import {
542
+ createCrmHandlers
543
+ } from "@contractspec/example.crm-pipeline";
544
+ import {
545
+ createSaasHandlers
546
+ } from "@contractspec/example.saas-boilerplate";
547
+ import {
548
+ createAgentHandlers
549
+ } from "@contractspec/example.agent-console";
550
+ import {
551
+ createWorkflowHandlers
552
+ } from "@contractspec/example.workflow-system";
553
+ import {
554
+ createMarketplaceHandlers
555
+ } from "@contractspec/example.marketplace";
556
+ import {
557
+ createIntegrationHandlers
558
+ } from "@contractspec/example.integration-hub";
559
+ import {
560
+ createAnalyticsHandlers
561
+ } from "@contractspec/example.analytics-dashboard";
562
+ import {
563
+ createPolicySafeKnowledgeAssistantHandlers
564
+ } from "@contractspec/example.policy-safe-knowledge-assistant";
565
+ import {
566
+ TemplateRuntimeContext,
567
+ useTemplateRuntime,
568
+ useTemplateComponents
569
+ } from "@contractspec/lib.example-shared-ui";
570
+ import { jsxDEV } from "react/jsx-dev-runtime";
571
+ "use client";
572
+ var { LocalRuntimeServices: LocalRuntimeServices2 } = web2;
573
+ function logBootstrapFailure(error) {
574
+ console.error(`
575
+ [TemplateRuntime] Bootstrap Failed
576
+ ==================================
577
+
578
+ The runtime failed to initialize. This usually happens because:
579
+ 1. The PostgreSQL Web environment (pglite) failed to load
580
+ 2. The schema migration failed
581
+ 3. The initial seed data could not be inserted
582
+
583
+ Check the console for specific database errors.
584
+ `.trim(), error);
585
+ }
586
+
587
+ class TemplateHandlers {
588
+ crm;
589
+ saas;
590
+ agent;
591
+ workflow;
592
+ marketplace;
593
+ integration;
594
+ analytics;
595
+ policySafeKnowledgeAssistant;
596
+ }
597
+ function TemplateRuntimeProvider({
598
+ templateId,
599
+ projectId = "default-project",
600
+ lazy = false,
601
+ children
602
+ }) {
603
+ const [context, setContext] = useState(null);
604
+ const [error, setError] = useState(null);
605
+ useEffect(() => {
606
+ let mounted = true;
607
+ async function bootstrap() {
608
+ try {
609
+ if (lazy)
610
+ return;
611
+ const template = getTemplate(templateId);
612
+ if (!template) {
613
+ throw new Error(`Template not found: ${templateId}`);
614
+ }
615
+ const runtime = new LocalRuntimeServices2;
616
+ await runtime.init({});
617
+ const installer = new TemplateInstaller({ runtime });
618
+ await installer.install(templateId, { projectId });
619
+ const client = web2.createLocalGraphqlClient(runtime);
620
+ const engine = await getTemplateEngine();
621
+ const handlers = new TemplateHandlers;
622
+ handlers.crm = createCrmHandlers(runtime.db);
623
+ handlers.saas = createSaasHandlers(runtime.db);
624
+ handlers.agent = createAgentHandlers(runtime.db);
625
+ handlers.workflow = createWorkflowHandlers(runtime.db);
626
+ handlers.marketplace = createMarketplaceHandlers(runtime.db);
627
+ handlers.integration = createIntegrationHandlers(runtime.db);
628
+ handlers.analytics = createAnalyticsHandlers(runtime.db);
629
+ handlers.policySafeKnowledgeAssistant = createPolicySafeKnowledgeAssistantHandlers(runtime.db);
630
+ const fetchData = async (presentationName) => {
631
+ if (presentationName === "crm-pipeline.dashboard") {
632
+ const [dealsResult, stages] = await Promise.all([
633
+ handlers.crm.listDeals({
634
+ projectId,
635
+ pipelineId: "pipeline-1",
636
+ limit: 50
637
+ }),
638
+ handlers.crm.getPipelineStages({ pipelineId: "pipeline-1" })
639
+ ]);
640
+ return {
641
+ data: {
642
+ deals: dealsResult.deals,
643
+ stages,
644
+ summary: {
645
+ total: dealsResult.total,
646
+ totalValue: dealsResult.totalValue
647
+ }
648
+ },
649
+ metadata: {
650
+ total: dealsResult.total,
651
+ timestamp: new Date,
652
+ source: "crm-pipeline"
653
+ }
654
+ };
655
+ }
656
+ if (presentationName === "crm-pipeline.deal.pipeline") {
657
+ const [dealsResult, stages] = await Promise.all([
658
+ handlers.crm.listDeals({
659
+ projectId,
660
+ pipelineId: "pipeline-1",
661
+ limit: 100
662
+ }),
663
+ handlers.crm.getPipelineStages({ pipelineId: "pipeline-1" })
664
+ ]);
665
+ return {
666
+ data: {
667
+ deals: dealsResult.deals,
668
+ stages,
669
+ total: dealsResult.total,
670
+ totalValue: dealsResult.totalValue
671
+ },
672
+ metadata: {
673
+ total: dealsResult.total,
674
+ timestamp: new Date,
675
+ source: "crm-pipeline"
676
+ }
677
+ };
678
+ }
679
+ if (presentationName === "saas-boilerplate.dashboard") {
680
+ const [projectsResult, subscription] = await Promise.all([
681
+ handlers.saas.listProjects({ projectId, limit: 10 }),
682
+ handlers.saas.getSubscription({ projectId })
683
+ ]);
684
+ return {
685
+ data: {
686
+ projects: projectsResult.items,
687
+ subscription,
688
+ summary: { totalProjects: projectsResult.total }
689
+ },
690
+ metadata: {
691
+ total: projectsResult.total,
692
+ timestamp: new Date,
693
+ source: "saas-boilerplate"
694
+ }
695
+ };
696
+ }
697
+ if (presentationName === "saas-boilerplate.project.list") {
698
+ const result = await handlers.saas.listProjects({
699
+ projectId,
700
+ limit: 50
701
+ });
702
+ return {
703
+ data: result.items,
704
+ metadata: {
705
+ total: result.total,
706
+ timestamp: new Date,
707
+ source: "saas-boilerplate"
708
+ }
709
+ };
710
+ }
711
+ if (presentationName === "saas-boilerplate.billing.settings") {
712
+ const subscription = await handlers.saas.getSubscription({
713
+ projectId
714
+ });
715
+ return {
716
+ data: subscription,
717
+ metadata: { timestamp: new Date, source: "saas-boilerplate" }
718
+ };
719
+ }
720
+ if (presentationName === "agent-console.dashboard") {
721
+ const [agentsResult, runsResult, toolsResult] = await Promise.all([
722
+ handlers.agent.listAgents({
723
+ projectId,
724
+ organizationId: "demo-org",
725
+ limit: 10
726
+ }),
727
+ handlers.agent.listRuns({ projectId, limit: 10 }),
728
+ handlers.agent.listTools({
729
+ projectId,
730
+ organizationId: "demo-org",
731
+ limit: 10
732
+ })
733
+ ]);
734
+ return {
735
+ data: {
736
+ agents: agentsResult.items,
737
+ runs: runsResult.items,
738
+ tools: toolsResult.items,
739
+ summary: {
740
+ totalAgents: agentsResult.total,
741
+ totalRuns: runsResult.total,
742
+ totalTools: toolsResult.total
743
+ }
744
+ },
745
+ metadata: { timestamp: new Date, source: "agent-console" }
746
+ };
747
+ }
748
+ if (presentationName === "agent-console.agent.list") {
749
+ const result = await handlers.agent.listAgents({
750
+ projectId,
751
+ organizationId: "demo-org",
752
+ limit: 50
753
+ });
754
+ return {
755
+ data: result.items,
756
+ metadata: {
757
+ total: result.total,
758
+ timestamp: new Date,
759
+ source: "agent-console"
760
+ }
761
+ };
762
+ }
763
+ if (presentationName === "agent-console.run.list") {
764
+ const result = await handlers.agent.listRuns({
765
+ projectId,
766
+ limit: 50
767
+ });
768
+ return {
769
+ data: result.items,
770
+ metadata: {
771
+ total: result.total,
772
+ timestamp: new Date,
773
+ source: "agent-console"
774
+ }
775
+ };
776
+ }
777
+ if (presentationName === "agent-console.tool.registry") {
778
+ const result = await handlers.agent.listTools({
779
+ projectId,
780
+ organizationId: "demo-org",
781
+ limit: 50
782
+ });
783
+ return {
784
+ data: result.items,
785
+ metadata: {
786
+ total: result.total,
787
+ timestamp: new Date,
788
+ source: "agent-console"
789
+ }
790
+ };
791
+ }
792
+ console.warn(`No data fetcher found for presentation: ${presentationName}`);
793
+ return {
794
+ data: null,
795
+ metadata: { timestamp: new Date, source: "unknown" }
796
+ };
797
+ };
798
+ if (mounted) {
799
+ setContext({
800
+ template,
801
+ runtime,
802
+ installer,
803
+ client,
804
+ templateId,
805
+ projectId,
806
+ engine,
807
+ handlers,
808
+ fetchData
809
+ });
810
+ }
811
+ } catch (err) {
812
+ logBootstrapFailure(err);
813
+ if (mounted) {
814
+ setError(err instanceof Error ? err : new Error("Unknown runtime error"));
815
+ }
816
+ }
817
+ }
818
+ bootstrap();
819
+ return () => {
820
+ mounted = false;
821
+ };
822
+ }, [templateId, projectId, lazy]);
823
+ const components = useTemplateComponents(templateId);
824
+ const contextValue = useMemo(() => {
825
+ if (!context)
826
+ return null;
827
+ return {
828
+ ...context,
829
+ components
830
+ };
831
+ }, [context, components]);
832
+ if (error) {
833
+ return /* @__PURE__ */ jsxDEV("div", {
834
+ className: "rounded border border-red-200 bg-red-50 p-4 text-red-500",
835
+ children: [
836
+ /* @__PURE__ */ jsxDEV("h3", {
837
+ className: "font-bold",
838
+ children: "Runtime Error"
839
+ }, undefined, false, undefined, this),
840
+ /* @__PURE__ */ jsxDEV("pre", {
841
+ className: "mt-2 overflow-auto text-xs",
842
+ children: error.message
843
+ }, undefined, false, undefined, this)
844
+ ]
845
+ }, undefined, true, undefined, this);
846
+ }
847
+ if (!contextValue) {
848
+ return /* @__PURE__ */ jsxDEV("div", {
849
+ className: "animate-pulse p-12 text-center text-gray-400",
850
+ children: "Initializing runtime environment..."
851
+ }, undefined, false, undefined, this);
852
+ }
853
+ return /* @__PURE__ */ jsxDEV(ApolloProvider, {
854
+ client: contextValue.client,
855
+ children: /* @__PURE__ */ jsxDEV(TemplateRuntimeContext.Provider, {
856
+ value: contextValue,
857
+ children
858
+ }, undefined, false, undefined, this)
859
+ }, undefined, false, undefined, this);
860
+ }
861
+ function useTemplateEngine() {
862
+ return useTemplateRuntime().engine;
863
+ }
864
+ function useTemplateHandlers() {
865
+ return useTemplateRuntime().handlers;
866
+ }
867
+ function useCrmHandlers() {
868
+ return useTemplateHandlers().crm;
869
+ }
870
+ function useSaasHandlers() {
871
+ return useTemplateHandlers().saas;
872
+ }
873
+ function useAgentHandlers() {
874
+ return useTemplateHandlers().agent;
875
+ }
876
+ function useWorkflowHandlers() {
877
+ return useTemplateHandlers().workflow;
878
+ }
879
+ function useMarketplaceHandlers() {
880
+ return useTemplateHandlers().marketplace;
881
+ }
882
+ function useIntegrationHandlers() {
883
+ return useTemplateHandlers().integration;
884
+ }
885
+ function useAnalyticsHandlers() {
886
+ return useTemplateHandlers().analytics;
887
+ }
888
+ export {
889
+ useWorkflowHandlers,
890
+ useTemplateHandlers,
891
+ useTemplateEngine,
892
+ useSaasHandlers,
893
+ useMarketplaceHandlers,
894
+ useIntegrationHandlers,
895
+ useCrmHandlers,
896
+ useAnalyticsHandlers,
897
+ useAgentHandlers,
898
+ searchExamples,
899
+ resetTemplateEngine,
900
+ listTemplates,
901
+ listExamples,
902
+ getTemplatesByModule,
903
+ getTemplateEngine,
904
+ getTemplate,
905
+ getExample,
906
+ getClonableTemplates,
907
+ createTemplateTransformEngine,
908
+ TemplateRuntimeProvider,
909
+ TemplateInstaller,
910
+ TemplateHandlers,
911
+ TEMPLATE_REGISTRY,
912
+ ExampleRegistry2 as ExampleRegistry,
913
+ EXAMPLE_REGISTRY2 as EXAMPLE_REGISTRY
914
+ };