@tacoshell/shell 0.0.0-stage → 0.1.1

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.
Files changed (63) hide show
  1. package/LICENSE +28 -0
  2. package/README.md +6 -2
  3. package/package.json +40 -4
  4. package/src/background.ts +41 -0
  5. package/src/core/bus.ts +210 -0
  6. package/src/core/cards.ts +33 -0
  7. package/src/core/contrib.ts +70 -0
  8. package/src/core/cron.ts +63 -0
  9. package/src/core/cronfriendly.ts +70 -0
  10. package/src/core/csv.ts +36 -0
  11. package/src/core/csvfeature.ts +57 -0
  12. package/src/core/datasets.ts +367 -0
  13. package/src/core/domshot.ts +81 -0
  14. package/src/core/guards.ts +36 -0
  15. package/src/core/hosts.ts +15 -0
  16. package/src/core/hotkeys.ts +44 -0
  17. package/src/core/indicators.ts +62 -0
  18. package/src/core/jobs.ts +37 -0
  19. package/src/core/localdata.ts +88 -0
  20. package/src/core/log.ts +91 -0
  21. package/src/core/markdown.ts +57 -0
  22. package/src/core/nav.ts +105 -0
  23. package/src/core/notifyrules.ts +31 -0
  24. package/src/core/page.ts +91 -0
  25. package/src/core/prefs.ts +119 -0
  26. package/src/core/router.ts +78 -0
  27. package/src/core/search.ts +65 -0
  28. package/src/core/services.ts +178 -0
  29. package/src/core/sessions.ts +93 -0
  30. package/src/core/startpage.ts +28 -0
  31. package/src/core/storage.ts +54 -0
  32. package/src/core/systemtools.ts +85 -0
  33. package/src/core/tabfit.ts +30 -0
  34. package/src/core/templates.ts +48 -0
  35. package/src/core/text.ts +6 -0
  36. package/src/core/toasts.ts +13 -0
  37. package/src/core/vault.ts +208 -0
  38. package/src/env.d.ts +2 -0
  39. package/src/index.ts +58 -0
  40. package/src/styles.css +391 -0
  41. package/src/types.ts +133 -0
  42. package/src/ui/ActionModal.tsx +22 -0
  43. package/src/ui/App.tsx +241 -0
  44. package/src/ui/ClearableInput.tsx +23 -0
  45. package/src/ui/CsvFeature.tsx +151 -0
  46. package/src/ui/Icon.tsx +8 -0
  47. package/src/ui/ItemFeature.tsx +39 -0
  48. package/src/ui/Markdown.tsx +24 -0
  49. package/src/ui/Rail.tsx +135 -0
  50. package/src/ui/RelatedMenu.tsx +57 -0
  51. package/src/ui/Search.tsx +111 -0
  52. package/src/ui/Sessions.tsx +76 -0
  53. package/src/ui/SidePanel.tsx +150 -0
  54. package/src/ui/TabBar.tsx +56 -0
  55. package/src/ui/ViewHost.tsx +142 -0
  56. package/src/ui/hooks.ts +28 -0
  57. package/src/ui/settings/Datasets.tsx +172 -0
  58. package/src/ui/settings/ReleaseNotes.tsx +96 -0
  59. package/src/ui/settings/ScheduleEditor.tsx +57 -0
  60. package/src/ui/settings/Settings.tsx +339 -0
  61. package/src/ui/settings/SettingsTabs.tsx +63 -0
  62. package/src/ui/settings/Templates.tsx +52 -0
  63. package/src/ui/useContrib.ts +36 -0
package/LICENSE ADDED
@@ -0,0 +1,28 @@
1
+ Taco Proprietary License
2
+
3
+ Copyright (c) 2026 ryanrutan. All rights reserved.
4
+
5
+ The software in this repository and in the published packages @tacoshell/sdk,
6
+ @tacoshell/shell and @tacoshell/cli (the "Software") is licensed, not sold.
7
+
8
+ 1. Permitted use. You may install the Software and use it to develop, build,
9
+ test, package and distribute your own applications and extensions, including
10
+ the Software's runtime as it is built into those applications. You may also
11
+ read the source code, and modify it for your own use (including your own
12
+ internal forks) to learn from it, debug your applications or adapt it to
13
+ your needs.
14
+
15
+ 2. Restrictions. Except as permitted above or by law, you may not: (a) publish
16
+ or distribute the Software or your modified versions of it on their own, or
17
+ as part of any framework, SDK, tool or competing product; (b) sublicense,
18
+ sell, rent or lease the Software; (c) remove or alter any copyright or
19
+ license notice.
20
+
21
+ 3. Ownership. The author retains all right, title and interest in the Software.
22
+ No rights are granted other than those expressly stated here.
23
+
24
+ 4. No warranty. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25
+ EXPRESS OR IMPLIED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM,
26
+ DAMAGES OR OTHER LIABILITY ARISING FROM THE SOFTWARE OR ITS USE.
27
+
28
+ 5. Termination. This license ends automatically if you breach it.
package/README.md CHANGED
@@ -1,3 +1,7 @@
1
- # Temporary Holding Version
1
+ # @tacoshell/shell
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Taco **runtime**: the React app shell (top nav, rail, 3rd-level bar, Activity Log, Help, Settings), the vault, message bus, notifications, header search, Sessions, datasets with schedules, templates and the MV3 service worker.
4
+
5
+ `taco-cli` bundles it into every app; module code never imports it (use `@tacoshell/sdk`). Ships TypeScript source.
6
+
7
+ Part of the Taco framework monorepo: see the repository root and `dev/GETTING-STARTED.md`.
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@tacoshell/shell",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "The Taco runtime: app shell (navigation, Activity Log, Help, Settings), vault, message bus, notifications, search, sessions, datasets.",
5
+ "keywords": [
6
+ "taco",
7
+ "chrome-extension",
8
+ "mv3",
9
+ "react"
10
+ ],
11
+ "license": "SEE LICENSE IN LICENSE",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/ryanrutan/tacoshell.git",
15
+ "directory": "packages/shell"
16
+ },
17
+ "homepage": "https://github.com/ryanrutan/tacoshell#readme",
18
+ "bugs": {
19
+ "url": "https://github.com/ryanrutan/tacoshell/issues"
20
+ },
21
+ "type": "module",
22
+ "exports": {
23
+ ".": "./src/index.ts",
24
+ "./background": "./src/background.ts",
25
+ "./package.json": "./package.json"
26
+ },
27
+ "files": [
28
+ "src",
29
+ "README.md",
30
+ "LICENSE"
31
+ ],
32
+ "dependencies": {
33
+ "@fortawesome/fontawesome-free": "^7.3.1",
34
+ "@tacoshell/sdk": "0.1.1",
35
+ "react": "^19.3.1",
36
+ "react-dom": "^19.3.1"
37
+ },
38
+ "publishConfig": {
39
+ "registry": "https://registry.npmjs.org",
40
+ "access": "public"
41
+ }
42
+ }
@@ -0,0 +1,41 @@
1
+ // The app's service worker: deliberately thin (CommunityOS ADR-002). Opens or focuses the app, runs the idle lock (ADR-042),
2
+ // and hands notification clicks to the app so its navigation guards still apply (ADR-041).
3
+
4
+ const APP_URL = chrome.runtime.getURL('app.html');
5
+
6
+ async function openApp(hash = '') {
7
+ const [tab] = await chrome.tabs.query({ url: `${APP_URL}*` });
8
+ if (tab?.id !== undefined) {
9
+ await chrome.tabs.update(tab.id, { active: true, ...(hash ? { url: APP_URL + hash } : {}) });
10
+ if (tab.windowId !== undefined) await chrome.windows.update(tab.windowId, { focused: true });
11
+ } else {
12
+ await chrome.tabs.create({ url: APP_URL + hash });
13
+ }
14
+ }
15
+
16
+ chrome.action.onClicked.addListener(() => void openApp());
17
+
18
+ chrome.runtime.onInstalled.addListener(() => chrome.alarms.create('taco-idle-lock', { periodInMinutes: 1 }));
19
+ chrome.runtime.onStartup.addListener(() => chrome.alarms.create('taco-idle-lock', { periodInMinutes: 1 }));
20
+
21
+ chrome.alarms.onAlarm.addListener(async (alarm) => {
22
+ if (alarm.name !== 'taco-idle-lock') return;
23
+ const { 'taco.settings': settings } = (await chrome.storage.local.get('taco.settings')) as { 'taco.settings'?: { idleLockMinutes?: number } };
24
+ const minutes = Number(settings?.idleLockMinutes ?? 15);
25
+ if (!minutes) return; // "Never"
26
+ const { 'taco.lastActivity': last, 'taco.vaultKey': key } = await chrome.storage.session.get(['taco.lastActivity', 'taco.vaultKey']);
27
+ if (key && Date.now() - Number(last ?? 0) > minutes * 60_000) {
28
+ await chrome.storage.session.remove('taco.vaultKey');
29
+ await chrome.storage.session.set({ 'taco.lockReason': 'idle' });
30
+ }
31
+ });
32
+
33
+ chrome.notifications?.onClicked.addListener(async (id) => {
34
+ const k = `taco.notify.${id}`;
35
+ const { [k]: open } = (await chrome.storage.session.get(k)) as Record<string, { view?: unknown } | null | undefined>;
36
+ await chrome.storage.session.remove(k);
37
+ chrome.notifications.clear(id);
38
+ // Not a URL: the app picks this up and opens it with showView, so a running bulk operation can't be thrown away (ADR-041).
39
+ if (open?.view) await chrome.storage.session.set({ 'taco.notifyOpen': open });
40
+ await openApp();
41
+ });
@@ -0,0 +1,210 @@
1
+ // The framework API each view gets (ADR-015, ADR-020, ADR-036, ADR-041). One instance per mounted view, scoped to its module:
2
+ // visibility checks use the caller's module, `storage` is namespaced by it, and the auto-log middleware names it.
3
+
4
+ import { featureUrl, type Context, type Framework, type Message, type NotificationMessage, type SendResult, type TopicRef, type ViewRef } from '@tacoshell/sdk';
5
+ import type { ReactNode } from 'react';
6
+ import { checkContext, NO_CONTEXT, type Page } from './page.ts';
7
+ import * as indicators from './indicators.ts';
8
+ import { dedupe, showSystem } from './notifyrules.ts';
9
+ import * as datasets from './datasets.ts';
10
+ import type { Registry } from '../types.ts';
11
+ import * as guards from './guards.ts';
12
+ import * as log from './log.ts';
13
+ import { settings } from './prefs.ts';
14
+ import * as router from './router.ts';
15
+ import * as services from './services.ts';
16
+ import * as templates from './templates.ts';
17
+ import { toast } from './toasts.ts';
18
+ import * as vault from './vault.ts';
19
+
20
+ let registry: Registry;
21
+ export const setRegistry = (r: Registry) => { registry = r; };
22
+ // Every dataset change publishes its standard `changed` event (ADR-026) with the new meta.
23
+ datasets.onChanged((d) => { for (const fn of subscribers.get(`${d.module}|dataset:${d.name}|changed`) ?? []) queueMicrotask(() => fn(datasets.meta(d))); });
24
+
25
+ const subscribers = new Map<string, Set<(payload: unknown) => void>>();
26
+ const topicKey = (t: { module: string; component: string; topic: string }) => `${t.module}|${t.component}|${t.topic}`;
27
+ const CONTEXT_LIMIT = 64 * 1024;
28
+
29
+ function plainJson(ctx: unknown): boolean {
30
+ try { return JSON.stringify(ctx).length <= CONTEXT_LIMIT && JSON.stringify(JSON.parse(JSON.stringify(ctx))) === JSON.stringify(ctx); } catch { return false; }
31
+ }
32
+
33
+ const fail = <T>(error: Exclude<SendResult<T>, { ok: true }>['error'], message: string): SendResult<T> => ({ ok: false, error, message });
34
+
35
+ /** Routes a request to its component. Services are the first component type with topics; datasets and templates come with the data release. */
36
+ async function route(callerModule: string, m: Message<unknown, unknown>): Promise<SendResult<unknown>> {
37
+ const { component, topic, module } = m.topic;
38
+ if (component.startsWith('service:')) {
39
+ const [type, name] = component.slice(8).split('/');
40
+ const s = services.find(type, name);
41
+ if (!s) return fail('unavailable', `No service ${type}/${name} in this app.`);
42
+ const st = services.stateOf(s);
43
+ if (topic === 'status') return { ok: true, value: { enabled: st.enabled, configured: services.isConfigured(s), healthy: !!st.lastTest?.ok, warning: st.lastTest?.status === 'warn', detail: st.lastTest?.detail } };
44
+ // The service's non-secret field values (declared defaults filled in): how a feature reads e.g. a board id. Secrets are never returned.
45
+ if (topic === 'config') return { ok: true, value: services.configOf(s) };
46
+ if (!st.enabled) return fail('unavailable', `${s.label} is turned off (Settings → Services).`);
47
+ if (!services.isConfigured(s)) return fail('unavailable', `${s.label} isn't set up yet (Settings → Services → ${s.label}).`);
48
+ if (topic === 'test') { const r = await services.test(s); return r.ok ? { ok: true, value: { ...r, healthy: true } } : fail('failed', r.detail); }
49
+ const decl = s.topics?.[topic];
50
+ if (!decl) return fail('invalid', `${s.label} has no topic "${topic}".`);
51
+ if (decl.visibility === 'protected' && callerModule !== s.module) return fail('denied', `"${topic}" is protected: only ${s.module} may call it (ADR-015).`);
52
+ const handler = services.implFor(s)?.topics?.[topic];
53
+ if (!handler) return fail('unavailable', `${s.label} doesn't implement "${topic}" yet.`);
54
+ try { return { ok: true, value: await handler(m.payload, services.contextFor(s)) }; } catch (e) { return fail('failed', (e as Error).message); }
55
+ }
56
+ if (component.startsWith('dataset:')) {
57
+ const d = datasets.find(module, component.slice(8));
58
+ if (!d) return fail('unavailable', `No dataset ${module}/${component.slice(8)} in this app.`);
59
+ if (topic === 'meta') return { ok: true, value: datasets.meta(d) };
60
+ // ADR-031: dataset contents are never readable while the vault is locked; topics answer "locked" (the UI offers the unlock prompt).
61
+ if (vault.status() !== 'unlocked') return fail('locked', `${d.label} is in the vault, which is locked.`);
62
+ const p = (m.payload ?? {}) as Record<string, unknown>;
63
+ try {
64
+ if (topic === 'query') return { ok: true, value: datasets.query(await datasets.rows(d), p as datasets.Query) };
65
+ if (topic === 'get') return { ok: true, value: datasets.getById(await datasets.rows(d), d, p.id) };
66
+ if (topic === 'set' || topic === 'delete') {
67
+ if (d.writes !== 'public' && callerModule !== d.module) return fail('denied', `Only ${d.module} may change ${d.label} (its "writes" is "module").`);
68
+ return { ok: true, value: topic === 'set' ? await datasets.upsert(d, (p.rows as datasets.Row[]) ?? []) : await datasets.remove(d, (p.ids as unknown[]) ?? []) };
69
+ }
70
+ if (topic === 'refresh') {
71
+ if (d.kind !== 'refreshable') return fail('unavailable', `${d.label} is import-only: import a CSV in Settings → Datasets.`);
72
+ await datasets.refresh(d, createFramework(d.module), { load: p.load === 'full' ? 'full' : undefined });
73
+ return { ok: true, value: datasets.meta(d) };
74
+ }
75
+ } catch (e) { return fail(e instanceof datasets.LockedError ? 'locked' : 'failed', (e as Error).message); }
76
+ return fail('invalid', `Datasets have no topic "${topic}".`);
77
+ }
78
+ if (component.startsWith('template:')) {
79
+ const t = registry.templates?.find((x) => x.module === module && x.name === component.slice(9));
80
+ if (!t) return fail('unavailable', `No template ${module}/${component.slice(9)} in this app.`);
81
+ if (topic === 'tokens') return { ok: true, value: t.tokens };
82
+ if (topic === 'render') {
83
+ if (vault.status() !== 'unlocked') return fail('locked', `${t.label} may have been edited, and edits are in the vault, which is locked.`);
84
+ try { return { ok: true, value: await templates.render(t, ((m.payload as { tokens?: Record<string, unknown> })?.tokens) ?? {}) }; } catch (e) { return fail('invalid', (e as Error).message); }
85
+ }
86
+ return fail('invalid', `Templates have no topic "${topic}".`);
87
+ }
88
+ if (component.startsWith('view:') && topic === 'open') {
89
+ const ok = await navigate({ kind: 'view', module, component }, (m.payload as { context?: Context })?.context);
90
+ return ok ? { ok: true, value: undefined } : fail('denied', 'Navigation was refused.');
91
+ }
92
+ return fail('unavailable', `${component} topics aren't available in this framework version yet.`);
93
+ }
94
+
95
+ export async function navigate(ref: ViewRef, context?: Context): Promise<boolean> {
96
+ const name = ref.component.replace(/^view:/, '');
97
+ const target = registry.views.find((v) => v.module === ref.module && v.name === name);
98
+ if (!target) { log.add('error', `showView: no view ${ref.module}/${name} in this app`); return false; }
99
+ if (context !== undefined && !plainJson(context)) { log.add('error', `showView: context for ${ref.module}/${name} must be plain JSON under 64 KB (ADR-036)`); return false; }
100
+ const problem = checkContext(target.context, context);
101
+ if (problem) { log.add('error', `showView: context for ${ref.module}/${name} doesn't match its declaration (${problem}) (ADR-052)`, context); return false; }
102
+ return router.go(router.href.view(ref.module, name), context, `${ref.module}/${name}`);
103
+ }
104
+
105
+ /** Notification keys shown in the last 24 h (memory: a reload starts a new window, as in v2). */
106
+ const seenKeys: Record<string, number> = {};
107
+ let unseenBadge = 0;
108
+ /** The toolbar badge counts Chrome notifications until the user comes back to the app. */
109
+ if (typeof addEventListener === 'function') addEventListener('focus', () => { if (unseenBadge && typeof chrome !== 'undefined' && chrome.action?.setBadgeText) { unseenBadge = 0; void chrome.action.setBadgeText({ text: '' }); } });
110
+
111
+ export function notify(callerModule: string, n: NotificationMessage) {
112
+ const decl = registry.notifications.find((x) => x.module === n.notification.module && x.id === n.notification.id);
113
+ const key = `${n.notification.module}/${n.notification.id}`;
114
+ if (!decl) { log.add('error', `Notification ${key} isn't declared in taco.module.json (ADR-028)`, undefined, callerModule); return; }
115
+ const prefs = settings.get().notifications;
116
+ const enabled = prefs.enabled && (prefs.items[key] ?? decl.default === 'enabled');
117
+ const title = n.payload.title ?? decl.label;
118
+ if (!enabled) { log.add('debug', `Notification ${key} is turned off; not shown: ${title}`, undefined, callerModule, 'notification'); return; }
119
+ if (vault.status() === 'locked') { log.add('debug', `Notification ${key} held back while the vault is locked (ADR-041): ${title}`, undefined, callerModule, 'notification'); return; }
120
+ if (!dedupe(n.payload.key ? `${key}:${n.payload.key}` : undefined, seenKeys)) { log.add('debug', `Notification ${key} (${n.payload.key}) already shown in the last 24 h: ${title}`, undefined, callerModule, 'notification'); return; }
121
+ log.add('info', `${title}: ${n.payload.message}`, n.payload.data, callerModule, 'notification');
122
+ if (decl.delivery !== 'system') toast(n.payload.message, 'info', title);
123
+ const inFront = typeof document !== 'undefined' && document.visibilityState === 'visible' && document.hasFocus();
124
+ const rule = showSystem(prefs, inFront);
125
+ if (decl.delivery !== 'toast' && !rule.show) log.add('debug', `Chrome notification for ${key} not shown: ${rule.why}`, undefined, callerModule, 'notification');
126
+ if (decl.delivery !== 'toast' && rule.show && prefs.badge && typeof chrome !== 'undefined' && chrome.action?.setBadgeText) {
127
+ unseenBadge++;
128
+ void chrome.action.setBadgeText({ text: String(unseenBadge) });
129
+ }
130
+ if (decl.delivery !== 'toast' && rule.show && typeof chrome !== 'undefined' && chrome.notifications?.create) {
131
+ const id = `taco:${key}:${n.payload.key ?? Date.now()}`;
132
+ // The click is handled by the service worker (the page may be closed): it hands { view, context } to the app (ADR-041).
133
+ const open = n.payload.view ? { view: n.payload.view, context: n.payload.context ?? null } : null;
134
+ void chrome.storage.session.set({ [`taco.notify.${id}`]: open });
135
+ chrome.notifications.create(id, { type: 'basic', iconUrl: 'icons/icon-128.png', title, message: n.payload.message, requireInteraction: prefs.sticky });
136
+ }
137
+ }
138
+
139
+ /** Stable snapshot for instances without a page (React's useSyncExternalStore loops on a new object per read). */
140
+ const NO_PAGE: Context = Object.freeze({});
141
+
142
+ /** Renders a view's slot; set by the UI layer (keeps this module free of React components). */
143
+ let renderSlot: (page: Page, name: string) => ReactNode = () => null;
144
+ export const setSlotRenderer = (fn: typeof renderSlot) => { renderSlot = fn; };
145
+
146
+ /** A framework instance for one module on one page. Panels from other modules on the same page share the page (ADR-053). */
147
+ export function createFramework(moduleId: string, page?: Page, featureView?: string): Framework {
148
+ // Indicators belong to the nav feature of the view this instance serves (its page's view, or the one a background job names).
149
+ const viewName = featureView ?? page?.key.slice(page.key.lastIndexOf('/') + 1);
150
+ const rv = viewName ? registry?.views.find((v) => v.module === moduleId && v.name === viewName) : undefined;
151
+ const flog = log.logger(moduleId === 'self' ? 'this app' : moduleId);
152
+ const noPage = () => { throw new Error('This framework instance is not attached to a page.'); };
153
+ // This module's datasets, live, with refresh and cancel: what its Settings → Datasets tab is built from (ADR-072).
154
+ const ownDatasets = {
155
+ ...datasets.infoStore(moduleId),
156
+ async refresh(name: string, opts?: { load?: 'full' | 'incremental' }): Promise<SendResult<ReturnType<typeof datasets.infoOf>>> {
157
+ const d = datasets.find(moduleId, name);
158
+ if (!d) return fail('unavailable', `${moduleId} has no dataset "${name}".`);
159
+ if (d.kind !== 'refreshable') return fail('unavailable', `${d.label} is import-only.`);
160
+ if (vault.status() !== 'unlocked') return fail('locked', `${d.label} is in the vault, which is locked.`);
161
+ try { await datasets.refresh(d, createFramework(moduleId), opts); return { ok: true, value: datasets.infoOf(d) }; }
162
+ catch (e) { return fail((e as Error).message === 'Cancelled' ? 'failed' : e instanceof datasets.LockedError ? 'locked' : 'failed', (e as Error).message); }
163
+ },
164
+ cancel(name: string) { const d = datasets.find(moduleId, name); if (d) datasets.cancel(d); },
165
+ };
166
+ return {
167
+ datasets: ownDatasets,
168
+ expose(ctx) { if (page && plainJson(ctx)) page.exposed.set(ctx ?? NO_CONTEXT); },
169
+ indicators: indicators.forFeature(rv ? `${rv.module}::${rv.nav.feature ?? rv.name}` : undefined),
170
+ urlOf: (t) => ('href' in t ? t.href : featureUrl(t.module, t.component.replace(/^view:/, ''))),
171
+ close: () => page?.close?.(),
172
+ log: flog,
173
+ async send<Req, Res>(m: Message<Req, Res>): Promise<SendResult<Res>> {
174
+ const label = `${m.topic.component}.${m.topic.topic}`;
175
+ log.add('debug', `send ${label}`, m.payload, moduleId);
176
+ const r = (await route(moduleId, m as Message<unknown, unknown>)) as SendResult<Res>;
177
+ if (!r.ok) log.add(r.error === 'failed' ? 'error' : 'warn', `${label}: ${r.message}`, undefined, moduleId);
178
+ return r;
179
+ },
180
+ publish<Req>(m: Message<Req, unknown>) {
181
+ log.add('trace', `publish ${m.topic.component}.${m.topic.topic}`, m.payload, moduleId);
182
+ for (const fn of subscribers.get(topicKey(m.topic)) ?? []) queueMicrotask(() => fn(m.payload));
183
+ },
184
+ subscribe<Req>(t: TopicRef<Req, unknown>, handler: (payload: Req) => void) {
185
+ const k = topicKey(t);
186
+ if (!subscribers.has(k)) subscribers.set(k, new Set());
187
+ const fn = handler as (p: unknown) => void;
188
+ subscribers.get(k)!.add(fn);
189
+ return () => { subscribers.get(k)?.delete(fn); };
190
+ },
191
+ showView: (ref, context) => navigate(ref as ViewRef, context as Context | undefined),
192
+ viewContext: page?.viewContext ?? { get: () => undefined, subscribe: () => () => {} },
193
+ page: page?.page ?? { get: () => NO_PAGE, subscribe: () => () => {}, set: noPage, refresh: noPage, onRefresh: () => () => {} },
194
+ tools: { add: (tool) => (page ? page.tools.add(tool) : () => {}) },
195
+ slot: (name) => (page ? renderSlot(page, name) : null),
196
+ notify: (n) => notify(moduleId, n),
197
+ guard: { block: guards.block, unsaved: guards.unsaved },
198
+ storage: {
199
+ async get<T>(key: string) { const raw = await vault.get(`module/${moduleId}/${key}`); return raw === undefined ? undefined : (JSON.parse(raw) as T); },
200
+ set: (key, value) => vault.put(`module/${moduleId}/${key}`, JSON.stringify(value)),
201
+ remove: (key) => vault.remove(`module/${moduleId}/${key}`),
202
+ },
203
+ setContextHandler(handler) {
204
+ if (!page) return;
205
+ page.handler = handler;
206
+ const current = page.viewContext.get();
207
+ if (current) queueMicrotask(() => handler(current));
208
+ },
209
+ };
210
+ }
@@ -0,0 +1,33 @@
1
+ // Cards (ADR-062): a module's sub-feature that any page can show. A card is wired to page-context entries, not to a page.
2
+ // It appears on a view when that view's PAGE context (what it was opened with, plus anything components set with page.set) satisfies the card's declaration,
3
+ // and it receives only those entries.
4
+
5
+ import type { Context } from '@tacoshell/sdk';
6
+ import type { RegistryCard } from '../types.ts';
7
+
8
+ const typeOk = (base: string, v: unknown) =>
9
+ base.endsWith('[]') ? Array.isArray(v) : base === 'object' ? typeof v === 'object' && v !== null && !Array.isArray(v) : base === 'unknown' || typeof v === base;
10
+
11
+ /**
12
+ * The entries of `ctx` a card is wired to, or null when the card doesn't apply: every required key ("slug": "string") present with the right type,
13
+ * a present optional key ("ticket": "number?") with the right type, and at least one declared key present (so an all-optional card needs one of them).
14
+ */
15
+ export function pick(decl: Record<string, string>, ctx: Context): Context | null {
16
+ const out: Context = {};
17
+ for (const [k, t] of Object.entries(decl)) {
18
+ const optional = t.endsWith('?');
19
+ const base = t.replace(/\?$/, '');
20
+ const v = ctx[k];
21
+ if (v === undefined || v === null) { if (optional) continue; return null; }
22
+ if (!typeOk(base, v)) return null;
23
+ out[k] = v;
24
+ }
25
+ return Object.keys(decl).length && !Object.keys(out).length ? null : out;
26
+ }
27
+
28
+ /** The cards that apply to a page right now, in display order (lower `order`, then module, then name). */
29
+ export function applicable(cards: RegistryCard[], ctx: Context): { card: RegistryCard; context: Context }[] {
30
+ return cards
31
+ .flatMap((card) => { const context = pick(card.context, ctx); return context ? [{ card, context }] : []; })
32
+ .sort((a, b) => a.card.order - b.card.order || a.card.module.localeCompare(b.card.module) || a.card.name.localeCompare(b.card.name));
33
+ }
@@ -0,0 +1,70 @@
1
+ // Related (menu) and Actions (ITEM right rail): which features contribute, and what they say about the feature being viewed.
2
+ // Only views that opted in (manifest `related: true` / `actions: true`) are asked: that flag is the index, so no other feature is ever iterated.
3
+
4
+ import { BUTTON_LABEL_MAX, featureUrl, type ButtonStyleType, type Contribution, type Contributor, type ContributorEnv, type FeatureInfo, type FeatureType } from '@tacoshell/sdk';
5
+ import type { CSSProperties } from 'react';
6
+ import { checkContext } from './page.ts';
7
+ import { clipText } from './text.ts';
8
+ import type { Context } from '@tacoshell/sdk';
9
+ import * as log from './log.ts';
10
+ import { viewKey, type Registry, type RegistryView } from '../types.ts';
11
+
12
+ export type ContribKind = 'related' | 'actions';
13
+ export type Handlers = Record<string, { contributeRelated?: Contributor; contributeActions?: Contributor } | undefined>;
14
+
15
+ /** A Related button, resolved: its action is a registry view of type ACTION and its label is clipped. */
16
+ export interface CollectedButton { label: string; styleType?: ButtonStyleType; styleClass?: string; styleInline?: CSSProperties; context?: Context; action: RegistryView }
17
+ export interface Collected { id: string; view: RegistryView; label: string; icon?: string; href: string; context?: Context; button?: CollectedButton }
18
+
19
+ /** Resolves a contribution's button against the registry; a button whose action isn't an ACTION view of this app is dropped (and logged), the link stays. */
20
+ function resolveButton(reg: Registry, owner: RegistryView, b: Contribution['button']): CollectedButton | undefined {
21
+ if (!b) return undefined;
22
+ const action = b.action && reg.views.find((v) => v.module === b.action.module && v.name === b.action.component.replace(/^view:/, ''));
23
+ if (!action || action.viewType !== 'ACTION') { log.add('error', `${viewKey(owner)}: a Related button's action must be an ACTION view of this app (${b.action ? `${b.action.module}/${b.action.component}` : 'no action given'})`, undefined, owner.module); return undefined; }
24
+ if (!b.label?.trim()) { log.add('error', `${viewKey(owner)}: a Related button needs a label`, undefined, owner.module); return undefined; }
25
+ return { label: clipText(b.label, BUTTON_LABEL_MAX), styleType: b.styleType, styleClass: b.styleClass, styleInline: b.styleInline, context: b.context, action };
26
+ }
27
+
28
+ /** Why an ACTION can't be opened with this context (it doesn't match the view's declaration), or null. */
29
+ export const actionProblem = (view: RegistryView, ctx: Context) => checkContext(view.context, ctx);
30
+
31
+ /** The nav feature key: `<module>::<feature or view name>` (matches core/nav.ts). */
32
+ export const featureKeyOf = (v: { module: string; name: string; nav: { feature?: string } }) => `${v.module}::${v.nav.feature ?? v.name}`;
33
+
34
+ export const infoOf = (v: RegistryView): FeatureInfo => ({ module: v.module, view: v.name, id: viewKey(v), feature: v.nav.feature ?? v.label, label: v.label, type: (v.viewType || 'GENERAL') as FeatureType, href: featureUrl(v.module, v.name) });
35
+
36
+ /** The opted-in contributors for a viewed feature: Related never includes ACTION views or the feature itself; Actions are ACTION views only. */
37
+ export const contributors = (reg: Registry, kind: ContribKind, current: RegistryView) =>
38
+ reg.views.filter((v) => (kind === 'related' ? v.related === true && v.viewType !== 'ACTION' && viewKey(v) !== viewKey(current) : v.actions === true && v.viewType === 'ACTION'));
39
+
40
+ export const byLabel = (a: Collected, b: Collected) => a.label.localeCompare(b.label, undefined, { sensitivity: 'base' }) || a.id.localeCompare(b.id);
41
+
42
+ /**
43
+ * Asks every contributor in parallel; `onItems` gets the sorted list so far each time one answers, so a menu can show as soon as the first
44
+ * item arrives. A contributor that throws is logged and skipped. Resolves when every contributor has answered.
45
+ */
46
+ export async function collect(opts: {
47
+ reg: Registry; kind: ContribKind; current: RegistryView; context: Context; handlers: Handlers; usable?: (v: RegistryView) => boolean;
48
+ /** The framework and logger each contributor gets (as its own module). */ env?: (v: RegistryView) => ContributorEnv;
49
+ onItems: (items: Collected[]) => void; cancelled?: () => boolean;
50
+ }): Promise<Collected[]> {
51
+ const { reg, kind, current, context, handlers, onItems } = opts;
52
+ const info = infoOf(current);
53
+ const items: Collected[] = [];
54
+ await Promise.all(contributors(reg, kind, current).filter((v) => opts.usable?.(v) ?? true).map(async (v) => {
55
+ const fn = kind === 'related' ? handlers[viewKey(v)]?.contributeRelated : handlers[viewKey(v)]?.contributeActions;
56
+ if (!fn) return;
57
+ try {
58
+ const out = ((await fn(info, context, opts.env?.(v) as ContributorEnv)) ?? []) as Contribution[];
59
+ if (opts.cancelled?.()) return;
60
+ for (const c of out) if (c && typeof c.label === 'string' && c.label.trim()) items.push({ id: `${viewKey(v)}|${c.label}`, view: v, label: c.label, icon: c.icon, href: featureUrl(v.module, v.name), context: c.context, button: kind === 'related' ? resolveButton(reg, v, c.button) : undefined });
61
+ if (out.length) onItems([...items].sort(byLabel));
62
+ } catch (e) { log.add('error', `${viewKey(v)}: ${kind === 'related' ? 'contributeRelated' : 'contributeActions'} failed: ${(e as Error).message}`, undefined, v.module); }
63
+ }));
64
+ return [...items].sort(byLabel);
65
+ }
66
+
67
+ /** The context the target receives: its own keys from the contribution, plus the viewed feature's exact context under the reserved `referrer`. */
68
+ export const targetContext = (c: Pick<Collected, 'context'>, viewed: Context): Context => ({ ...(c.context ?? {}), referrer: viewed });
69
+ /** The context a Related button's action receives: its own `context` as the primary, the viewed feature's under `referrer`. */
70
+ export const buttonContext = (b: Pick<CollectedButton, 'context'>, viewed: Context): Context => ({ ...(b.context ?? {}), referrer: viewed });
@@ -0,0 +1,63 @@
1
+ // Minimal 5-field crontab (minute hour day-of-month month day-of-week) for dataset schedules (ported from CommunityOS v2 lib/cron.js).
2
+ // Supports *, lists (1,3), ranges (1-5), steps (*/15, 1-10/2), day-of-week 0-7 (0 and 7 = Sunday) and the nth-weekday form `D#n` (`1#1` = the first Monday).
3
+ // Like classic cron, when both day-of-month and day-of-week are restricted a day matches if EITHER does. Local time.
4
+
5
+ const RANGES: [number, number][] = [[0, 59], [0, 23], [1, 31], [1, 12], [0, 7]];
6
+
7
+ function field(src: string, [lo, hi]: [number, number]): Set<number> {
8
+ const out = new Set<number>();
9
+ for (const part of String(src).split(',')) {
10
+ const [range, stepText] = part.split('/');
11
+ const step = stepText == null ? 1 : Number(stepText);
12
+ if (!Number.isInteger(step) || step < 1) throw new Error(`bad step in “${part}”`);
13
+ let a: number, b: number;
14
+ if (range === '*') [a, b] = [lo, hi];
15
+ else if (/^\d+$/.test(range)) { a = Number(range); b = stepText == null ? a : hi; }
16
+ else if (/^\d+-\d+$/.test(range)) [a, b] = range.split('-').map(Number);
17
+ else throw new Error(`can’t read “${part}”`);
18
+ if (a < lo || b > hi || a > b) throw new Error(`“${part}” is outside ${lo}-${hi}`);
19
+ for (let v = a; v <= b; v += step) out.add(v);
20
+ }
21
+ return out;
22
+ }
23
+
24
+ export interface Cron { m: Set<number>; h: Set<number>; dom: Set<number>; mon: Set<number>; dow: Set<number>; nth: { d: number; n: number }[]; domAny: boolean; dowAny: boolean }
25
+
26
+ /** "m h dom mon dow" → parsed fields; throws Error with a readable reason. */
27
+ export function parseCron(expr: string): Cron {
28
+ const p = String(expr ?? '').trim().split(/\s+/);
29
+ if (p.length !== 5) throw new Error('a crontab needs 5 fields: minute hour day-of-month month day-of-week');
30
+ const nth: Cron['nth'] = [];
31
+ const dowPlain = p[4].split(',').filter((t) => {
32
+ const x = /^([0-7])#([1-5])$/.exec(t);
33
+ if (x) nth.push({ d: Number(x[1]) % 7, n: Number(x[2]) });
34
+ else if (t.includes('#')) throw new Error(`can’t read “${t}” (use day#1-5, e.g. 1#1 = the first Monday)`);
35
+ return !x;
36
+ }).join(',');
37
+ const [m, h, dom, mon] = p.slice(0, 4).map((s, i) => field(s, RANGES[i]));
38
+ const dow = dowPlain ? field(dowPlain, RANGES[4]) : new Set<number>();
39
+ if (dow.has(7)) { dow.delete(7); dow.add(0); }
40
+ return { m, h, dom, mon, dow, nth, domAny: p[2] === '*', dowAny: p[4] === '*' };
41
+ }
42
+ export const isValidCron = (expr: string) => { try { parseCron(expr); return true; } catch { return false; } };
43
+
44
+ const dayOk = (c: Cron, d: Date) => {
45
+ const byDom = c.dom.has(d.getDate());
46
+ const byDow = c.dow.has(d.getDay()) || c.nth.some((x) => x.d === d.getDay() && x.n === Math.ceil(d.getDate() / 7));
47
+ return c.domAny && c.dowAny ? true : c.domAny ? byDow : c.dowAny ? byDom : byDom || byDow;
48
+ };
49
+
50
+ /** The first matching minute strictly after `from` (ms) → ms, or null when none within 5 years (e.g. 31 Feb). */
51
+ export function cronNext(expr: string | Cron, from = Date.now()): number | null {
52
+ const c = typeof expr === 'string' ? parseCron(expr) : expr;
53
+ const d = new Date(from); d.setSeconds(0, 0); d.setMinutes(d.getMinutes() + 1);
54
+ const limit = from + 5 * 366 * 864e5;
55
+ while (d.getTime() < limit) {
56
+ if (!c.mon.has(d.getMonth() + 1)) { d.setMonth(d.getMonth() + 1, 1); d.setHours(0, 0, 0, 0); continue; }
57
+ if (!dayOk(c, d)) { d.setDate(d.getDate() + 1); d.setHours(0, 0, 0, 0); continue; }
58
+ if (!c.h.has(d.getHours())) { d.setHours(d.getHours() + 1, 0, 0, 0); continue; }
59
+ if (!c.m.has(d.getMinutes())) { d.setMinutes(d.getMinutes() + 1, 0, 0); continue; }
60
+ return d.getTime();
61
+ }
62
+ return null;
63
+ }
@@ -0,0 +1,70 @@
1
+ // Plain-English view of a crontab for the dataset Schedule editor (ported from CommunityOS v2 lib/cronfriendly.js).
2
+ // The crontab is what is PERSISTED; the editor shows it as a form (How often · time · days) and reads it back. Anything the form can't express is "custom". Local time.
3
+
4
+ export type Mode = 'manual' | 'minutes' | 'hours' | 'daily' | 'weekdays' | 'weekly' | 'monthly' | 'custom';
5
+ export const MODES: [Mode, string][] = [['manual', 'Manual only'], ['minutes', 'Every few minutes'], ['hours', 'Every few hours'], ['daily', 'Every day'], ['weekdays', 'Every weekday (Mon–Fri)'],
6
+ ['weekly', 'Certain days of the week'], ['monthly', 'Once a month'], ['custom', 'Custom (crontab)…']];
7
+ export const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
8
+ export const MINUTE_STEPS = [1, 2, 5, 10, 15, 20, 30], HOUR_STEPS = [1, 2, 3, 4, 6, 8, 12];
9
+
10
+ export interface Form { mode: Mode; every: number; minute: number; time: string; days: number[]; day: number; cron: string }
11
+
12
+ const pad = (n: number) => String(n).padStart(2, '0');
13
+ const clock = (hh: number, mm: number) => `${hh % 12 || 12}:${pad(mm)} ${hh < 12 ? 'AM' : 'PM'}`;
14
+ const num = /^\d+$/;
15
+ const split = (t = '02:00'): [number, number] => { const [h, m] = String(t).split(':').map((x) => Number(x) || 0); return [Math.min(23, Math.max(0, h)), Math.min(59, Math.max(0, m))]; };
16
+
17
+ /** crontab (or null / '') → the editor's form state. */
18
+ export function toForm(cron?: string | null): Form {
19
+ const base: Form = { mode: 'manual', every: 15, minute: 0, time: '02:00', days: [1], day: 1, cron: cron || '0 2 * * *' };
20
+ if (!cron || !String(cron).trim()) return base;
21
+ const f = String(cron).trim().split(/\s+/);
22
+ const custom: Form = { ...base, mode: 'custom', cron: String(cron).trim() };
23
+ if (f.length !== 5 || f[3] !== '*') return custom;
24
+ const [m, h, dom, , dow] = f;
25
+ const t = () => `${pad(Number(h))}:${pad(Number(m))}`;
26
+ let x: RegExpExecArray | null;
27
+ if ((x = /^\*\/(\d+)$/.exec(m)) && h === '*' && dom === '*' && dow === '*') return MINUTE_STEPS.includes(Number(x[1])) ? { ...base, mode: 'minutes', every: Number(x[1]) } : custom;
28
+ if (num.test(m) && Number(m) < 60 && dom === '*' && dow === '*' && (h === '*' || /^\*\/\d+$/.test(h))) {
29
+ const n = h === '*' ? 1 : Number(h.slice(2));
30
+ return HOUR_STEPS.includes(n) ? { ...base, mode: 'hours', every: n, minute: Number(m) } : custom;
31
+ }
32
+ if (!num.test(m) || !num.test(h) || Number(m) > 59 || Number(h) > 23) return custom;
33
+ if (dom === '*' && dow === '*') return { ...base, mode: 'daily', time: t() };
34
+ if (dom === '*' && dow === '1-5') return { ...base, mode: 'weekdays', time: t() };
35
+ if (dom === '*' && /^\d(,\d)*$/.test(dow)) return { ...base, mode: 'weekly', time: t(), days: [...new Set(dow.split(',').map((d) => Number(d) % 7))].sort() };
36
+ if (dow === '*' && num.test(dom) && Number(dom) >= 1 && Number(dom) <= 28) return { ...base, mode: 'monthly', time: t(), day: Number(dom) };
37
+ return custom;
38
+ }
39
+
40
+ /** form state → crontab (null = manual). */
41
+ export function fromForm(s: Form): string | null {
42
+ const [hh, mm] = split(s.time);
43
+ switch (s.mode) {
44
+ case 'minutes': return `*/${Number(s.every) || 15} * * * *`;
45
+ case 'hours': return `${Math.min(59, Math.max(0, Number(s.minute) || 0))} ${Number(s.every) === 1 ? '*' : `*/${Number(s.every) || 1}`} * * *`;
46
+ case 'daily': return `${mm} ${hh} * * *`;
47
+ case 'weekdays': return `${mm} ${hh} * * 1-5`;
48
+ case 'weekly': return `${mm} ${hh} * * ${(s.days?.length ? [...s.days].sort() : [1]).join(',')}`;
49
+ case 'monthly': return `${mm} ${hh} ${Math.min(28, Math.max(1, Number(s.day) || 1))} * *`;
50
+ case 'custom': return String(s.cron || '').trim() || null;
51
+ default: return null;
52
+ }
53
+ }
54
+
55
+ /** "Every day at 2:00 AM" … */
56
+ export function describeCron(cron?: string | null): string {
57
+ if (!cron || !String(cron).trim()) return 'Manual only';
58
+ const s = toForm(cron);
59
+ const [hh, mm] = split(s.time);
60
+ const at = clock(hh, mm);
61
+ switch (s.mode) {
62
+ case 'minutes': return s.every === 1 ? 'Every minute' : `Every ${s.every} minutes`;
63
+ case 'hours': return s.every === 1 ? (s.minute === 0 ? 'Every hour, on the hour' : `Every hour, at :${pad(s.minute)} past`) : `Every ${s.every} hours, at :${pad(s.minute)} past the hour`;
64
+ case 'daily': return `Every day at ${at}`;
65
+ case 'weekdays': return `Every weekday (Mon–Fri) at ${at}`;
66
+ case 'weekly': return `Every ${s.days.map((d) => DAYS[d]).join(', ')} at ${at}`;
67
+ case 'monthly': return `On day ${s.day} of every month at ${at}`;
68
+ default: return `Custom crontab: ${s.cron}`;
69
+ }
70
+ }
@@ -0,0 +1,36 @@
1
+ // RFC 4180 CSV parse / stringify (ADR-045, as CommunityOS lib/csv.js): quoted fields, "" escapes, CRLF or LF, a BOM, embedded newlines.
2
+
3
+ export function parseCsv(text: string): string[][] {
4
+ const rows: string[][] = [];
5
+ let row: string[] = [];
6
+ let field = '';
7
+ let quoted = false;
8
+ const s = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
9
+ for (let i = 0; i < s.length; i++) {
10
+ const ch = s[i];
11
+ if (quoted) {
12
+ if (ch === '"') {
13
+ if (s[i + 1] === '"') { field += '"'; i++; } else quoted = false;
14
+ } else field += ch;
15
+ continue;
16
+ }
17
+ if (ch === '"' && field === '') quoted = true;
18
+ else if (ch === ',') { row.push(field); field = ''; }
19
+ else if (ch === '\n' || ch === '\r') {
20
+ if (ch === '\r' && s[i + 1] === '\n') i++;
21
+ row.push(field); field = '';
22
+ rows.push(row); row = [];
23
+ } else field += ch;
24
+ }
25
+ if (field !== '' || row.length) { row.push(field); rows.push(row); }
26
+ return rows.filter((r) => !(r.length === 1 && r[0] === ''));
27
+ }
28
+
29
+ const quote = (v: unknown) => {
30
+ const s = v === null || v === undefined ? '' : typeof v === 'object' ? JSON.stringify(v) : String(v);
31
+ return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
32
+ };
33
+
34
+ export function stringifyCsv(columns: string[], rows: Record<string, unknown>[]): string {
35
+ return [columns.map(quote).join(','), ...rows.map((r) => columns.map((c) => quote(r[c])).join(','))].join('\r\n') + '\r\n';
36
+ }