@bitakit/core 0.1.0 → 0.1.2

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 (48) hide show
  1. package/README.md +174 -325
  2. package/assets/bitakit-banner.png +0 -0
  3. package/assets/bitakit-logo-dark.svg +11 -0
  4. package/assets/bitakit-logo.svg +11 -0
  5. package/discovery/generate.mjs +2 -8
  6. package/dist/actions/action-list.d.ts +1 -1
  7. package/dist/actions/action-list.js +53 -4
  8. package/dist/actions/action.d.ts +3 -3
  9. package/dist/actions/types.d.ts +4 -0
  10. package/dist/app/access.js +2 -1
  11. package/dist/app/service-aliases.d.ts +4 -0
  12. package/dist/app/service-aliases.js +14 -0
  13. package/dist/app/types.d.ts +12 -1
  14. package/dist/auth-navigation.d.ts +13 -0
  15. package/dist/auth-navigation.js +33 -0
  16. package/dist/contracts.d.ts +5 -0
  17. package/dist/contributions/command.js +9 -0
  18. package/dist/contributions/index.d.ts +1 -0
  19. package/dist/core.d.ts +4 -0
  20. package/dist/core.js +2 -0
  21. package/dist/definitions.d.ts +30 -4
  22. package/dist/discovered.d.ts +9 -5
  23. package/dist/discovered.js +3 -2
  24. package/dist/events/action-setup.d.ts +19 -0
  25. package/dist/events/action-setup.js +24 -0
  26. package/dist/events/service.d.ts +18 -0
  27. package/dist/events/service.js +98 -0
  28. package/dist/events/types.d.ts +19 -0
  29. package/dist/events/types.js +1 -0
  30. package/dist/replacements.d.ts +1 -1
  31. package/dist/runtime.d.ts +2 -0
  32. package/dist/runtime.js +18 -2
  33. package/dist/service-key.d.ts +6 -0
  34. package/dist/service-key.js +0 -1
  35. package/dist/services.d.ts +2 -1
  36. package/dist/services.js +5 -1
  37. package/docs/auth.md +106 -0
  38. package/docs/events.md +157 -0
  39. package/docs/file-contributions.md +13 -0
  40. package/docs/reference.md +404 -0
  41. package/docs/todo-tutorial.md +88 -0
  42. package/examples/todos/actions/create.mjs +7 -0
  43. package/examples/todos/actions/delete.mjs +14 -0
  44. package/examples/todos/actions/list.mjs +7 -0
  45. package/examples/todos/plugin.mjs +11 -0
  46. package/examples/todos/services/tasks.mjs +30 -0
  47. package/examples/todos.mjs +17 -0
  48. package/package.json +6 -3
@@ -0,0 +1,404 @@
1
+ # Core reference
2
+
3
+ ## Public app access and installed plugins
4
+
5
+ Local plugins need only their contribution files:
6
+
7
+ ```text
8
+ src/plugins/documents/
9
+ services/documents.ts
10
+ actions/create.ts
11
+ ```
12
+
13
+ Each immediate plugin folder supplies its default plugin ID. `plugin.config.ts` is
14
+ optional. `defineService({ create: () => ({ ... }) })` infers its public name from the
15
+ relative service path; `defineAction({ execute: ({ app }) => ... })` infers its ID
16
+ from the plugin ID and action path. Explicit `id` values override these defaults.
17
+ Discovery generates registration and types, including service method inputs and outputs.
18
+
19
+ Use `app.services.documents` and `app.actions.documents.create.execute()`. Action references
20
+ delegate to the existing ActionList, preserving execution guards and lifecycle behavior.
21
+ Internal actions stay out of enumeration. React ActionButton, ActionBinding and useAction
22
+ accept these references; a reference must belong to the same provider's ActionList.
23
+
24
+ `app.config.<plugin>.<path>` reads the immutable resolved configuration snapshot, including
25
+ host overrides. `defineConfig({ defaults: { pageSize: 20 } })` works without a schema;
26
+ optional schemas retain their parse contract. Low-level scoped reads remain available through
27
+ `runtime.configuration` and the existing action/service config context.
28
+ Optional packages can project instance-local facades through `appExtensions` and augment
29
+ `AppExtensionMap`. Core owns no Settings implementation or duplicate state.
30
+
31
+ Service definitions use `exposeAs` to name their existing instance in `app.services`. Public names must be unique within the service namespace. Available since Core 0.1.1.
32
+
33
+ ```ts
34
+ const documents = serviceKey<Documents>('editor.documents');
35
+ export default function documentsPlugin() {
36
+ return definePlugin({
37
+ id: 'documents',
38
+ services: [provideService(documents, { exposeAs: 'documents', create: () => createDocumentsService() })],
39
+ });
40
+ }
41
+ ```
42
+
43
+ `runtime.app.services.documents` resolves that same container instance. `defineService` supports the same `exposeAs` option. Discovery defaults it to the explicit ID or relative service path, so normal file-based definitions need neither IDs nor name mappings. Existing `publicServices` remains supported for compatibility and aliases to externally supplied services; it is not a private/public access boundary. Required access reports
44
+ FoundationServiceError (`code`, `service`, `reason`, optional `plugin`) when unavailable.
45
+ `app.optional.services.documents` returns undefined before mount or when unavailable. After mount,
46
+ `app.ready` is true; disposal makes optional reads unavailable again. Obtaining a service
47
+ does not subscribe to its data. Existing dependency checks and reverse cleanup still apply.
48
+ Do not cache service instances across runtime replacement.
49
+
50
+ The React hook `useFoundationApp` lives in UI and follows readiness; Core remains usable
51
+ without React. Its default public contract is generated from local contributions and installed opt-in plugins.
52
+ Manual typed compositions use `FoundationApp<PublicServicesOf<typeof plugins>>` or the
53
+ corresponding hook generic. Keep precise factory return types instead of widening them to
54
+ `Plugin` if callers need public-service completion.
55
+
56
+ A package can opt into discovery with public package exports and metadata:
57
+
58
+ ```json
59
+ {
60
+ "exports": {
61
+ "./package.json": "./package.json",
62
+ "./foundation": "./dist/foundation.js"
63
+ },
64
+ "foundation": { "plugin": "./foundation" }
65
+ }
66
+ ```
67
+
68
+ The plugin entry default-exports a synchronous factory returning one Plugin. By default it
69
+ receives no arguments. Optional metadata `"configuration": "shell"` passes that path from the
70
+ resolved root app config (including defaults and app overrides), or `{}` when absent. It describes services/providers; it must not acquire external resources at factory
71
+ time. Core owns their creation and cleanup. Direct dependencies and optionalDependencies
72
+ are considered; transitive and development dependencies are not automatically activated.
73
+ Only packages exposing their package.json and explicit Foundation metadata participate.
74
+ `foundation.config.ts` can disable all package contributions with `packages: false`, or
75
+ individual packages with `packages: { 'package-name': false }`.
76
+
77
+ An optional `foundation.discovery` export default-exports a Node-safe function returning
78
+ contribution kind descriptors. Explicit `kinds` overrides replace package defaults by name.
79
+ Client plugin factories are never executed by build discovery; these discovery adapters
80
+ are trusted build code. Removing/disabling a package removes its generated import and types.
81
+ Local source discovery continues through the same existing pipeline.
82
+
83
+ Source responsibilities: `app/types.ts` owns public typing, `app/access.ts` projects current
84
+ services, and `app/service-error.ts` owns diagnostics. `discovery/packages.mjs` reads opt-in
85
+ metadata; `discovery/generate.mjs` emits imports and app types. None is a second runtime registry.
86
+
87
+ Framework-independent Actions, plugin lifecycle and services. React bindings live in the separate @bitakit/ui package. Import general APIs from `@bitakit/core` and UI APIs from `@bitakit/ui`. This package does not create another ActionProvider, settings store, router, authentication session, or API client.
88
+
89
+ The shared filename grammar, configuration service, migration rules and current limits are documented in [File contributions and config](file-contributions.md).
90
+
91
+ ## Small plugin
92
+
93
+ ```ts
94
+ // actions/invite.form-action.ts
95
+ import { defineFormAction } from '@bitakit/core';
96
+
97
+ export default defineFormAction({
98
+ groups: ['userManagement.dropdownMenu'],
99
+ requires: ['users'],
100
+ fields: {
101
+ email: { type: 'email', required: true },
102
+ },
103
+ async submit(values, { services }) {
104
+ return services.users.invite(values);
105
+ },
106
+ });
107
+ ```
108
+
109
+ File discovery infers `users.invite` from the plugin ID and relative action filename. Standalone React configs supply an explicit `id`, or call `resolveContribution(definition, inferredId)` in their own build integration. No setup file is needed for declarative groups. Groups are created on first use; a central group catalog is optional. Explicit typed ActionGroup objects remain supported. A group does not create UI: bind a menu to its ID.
110
+
111
+ ```tsx
112
+ <ActionMenu group="userManagement.dropdownMenu" label="User actions" />
113
+ ```
114
+
115
+ Optional `setup` runs after all selected plugins' actions are registered. Its scoped facade tracks registrations and placements; no manual cleanup is required for `getGroup().add()` or `attach()`. It can return cleanup for its own external subscriptions. Async setup is intentionally unsupported. Invalid group IDs, duplicate action IDs and missing/cyclic dependencies fail explicitly. Failed setup rolls back the contributions already installed.
116
+
117
+ `add()` accepts a core ActionDefinition. Declarative forms/dialogs are supplied in the plugin's `actions` contribution array (or discovered by the Next adapter); use `attach()` for their placements. `attach()` adds a placement without changing the action's global order. Set `order` on the action definition when ordering matters.
118
+
119
+ ## Optional conventions
120
+
121
+ Explicit properties win over conventions. A definition with `id: 'custom.invite'` keeps that ID even if its file moves. With no `title`, the default key is `<id>.title`; each field uses `<id>.fields.<name>`. `title`, `description` and field `label` accept a translation key when present in the current catalog, otherwise literal text. There are no separate action key properties. Button, menu, dialog heading and submit button read the same action title; the dialog reads its action description. Missing labels fall back to a readable ID/field name. Supply a translator with `has(key)` (such as next-intl's translator) to avoid querying missing keys.
122
+
123
+ `success` and `failure` each accept a literal string, `{ messageKey, values? }`, `{ message }`, a synchronous callback returning any of these, or `false`. Absent feedback, `false`, empty messages and callback `undefined` are silent. Success callbacks receive `{ result, input, services }`; failure callbacks receive `{ error, input, services }`. Results retain the inferred return type of `submit`/`execute`; errors are `unknown` and should be narrowed before use. Feedback callbacks are for presentation and cannot reverse an already completed operation if they throw.
124
+
125
+ There are no inferred outcome messages. Explicit `messageKey` and `values` use the current translator; literal strings remain literal. Raw errors are never used as display text.
126
+
127
+ ```ts
128
+ success: ({ result }) => ({
129
+ messageKey: 'users.invite.created',
130
+ values: { invitationId: result.invitationId },
131
+ }),
132
+ failure: ({ error }) => error instanceof InviteLimitError
133
+ ? { messageKey: 'users.invite.limit' }
134
+ : undefined, // default failure text
135
+ ```
136
+
137
+ `success: false` hides the success message; forms still close. Set `closeOnSuccess: false` to keep the form open. Existing `{ closeDialog: false, messageKey: '...' }` feedback is also supported; `closeOnSuccess` wins when both are supplied. `failure: false` leaves a failed form open silently. Opening a form/dialog never displays a success message. Commands report through the provider's `notify`; forms do so on the normal submission path, including custom render's `submit` function. The low-level `<id>.submit` action is an internal execution primitive; programmatic consumers should use `runtime.submitForm(runtime.getSnapshot().definition, values)` for the full form flow.
138
+
139
+ Set `conventions: false` on an action to require explicit ID/title and disable inferred field keys. Explicit messages and groups still work. The Next discovery config offers the same switch globally; an action can override it. Core actions registered directly in the ActionList remain unchanged.
140
+
141
+ Command failures throw `ActionFailure`: `feedback` contains the selected string or `false`, and `cause` retains the original error. The runtime observes failed execution once and sends explicit feedback to `notify(message, kind)`, where kind is `success` or `failure`. Do not toast the same `ActionFailure` again in `onError`. Form failures also retain their inline feedback. The notifier may return a promise; throws and rejections cannot change execution outcomes. `setNotifier` returns owner-safe cleanup. No parallel execution or notification registry is introduced.
142
+
143
+ ## Host integration
144
+
145
+ FoundationProvider owns the root ActionProvider or reuses an existing outer provider. Supply stable `config`, `ui`, `translate`, localized `labels`, and an optional outcome-aware `notify(message, kind)` callback to the generic UI entry. The Next adapter provides standard UI, labels and navigation defaults. The package owns form state, validation, pending/error behavior and lifecycle.
146
+
147
+ A standalone React application can supply an explicit `FoundationConfig`; Next is not required. The provider owns no global singleton. Services are created on mount, in dependency order, and disposed in reverse order. Their optional `dispose(instance)` handles external resources. Locale changes update presentation through the original registrations without recreating services or pending actions. Changing the config object replaces that plugin composition deliberately.
148
+
149
+ Form actions register the public opening action and an `<id>.submit` registration flagged `internal`: it stays executable so interceptors, pending state and execution events apply, but `useActions()` and group views hide it. Both use the existing execution engine. Submission validates required/text/email/select fields even if invoked programmatically; the form maintains drafts on failures. Disable/hide checks apply again at execution. Closing is blocked during a pending submission. Only one foundation dialog is open at a time. `render` can override the form body using `values`, `setValue`, `submit`, `pending`, `enabled`, and `error`. `defineDialogAction` provides a custom body without form submission machinery.
150
+
151
+ `ActionBoundary` gates children on current action visibility/enabled state, fails closed for missing actions, and accepts a fallback. It is a UI gate, never a substitute for server authorization. Hiding/unmounting children discards their local React state.
152
+
153
+ ## Types and translation
154
+
155
+ Core discovery generates a `ConfigMap` for module config and a `ServiceMap` augmentation using each service factory's return type, and an `ActionMap` augmentation from discovered action definitions: the effective ID (`replaces`, then an explicit `id`, then the file path) maps to the definition's input and result types, so `useAction`, `list.execute` and the UI bindings autocomplete IDs and type their input and completed `value`. Class and function exports establish their ID at construction and are excluded; augment `ActionMap` manually for those. With global `conventions: false` only explicit IDs are emitted. Unknown IDs remain allowed unless `ActionMapOptions` is augmented with `{ strict: true }`. Explicit consumers may augment `@bitakit/core` themselves. `requires` declares runtime dependencies; TypeScript provides method input/output inference. API responses still need runtime validation in the service.
156
+
157
+ `mergePluginMessages` merges each key in this priority: app current language, plugin current language, app fallback language, plugin fallback language (highest priority first). Packaged catalogs are exported by their owning package; local discovery catalogs retain their plugin namespace. Pass the result to your normal translation provider. The package does not create a second locale store.
158
+
159
+ ## Scope
160
+
161
+ Implemented: local trusted plugins, synchronous typed service factories, actions/forms/dialogs, scoped group placement, lifecycle, translation composition and UI boundaries. Existing SettingsCatalog contributions continue through the settings package; there is no parallel settings loader. Remote plugin installation, untrusted code sandboxes, server frameworks and database migrations are not included in Core. Next.js and experimental TanStack integrations live in separate packages.
162
+
163
+ ### Shared unavailable message
164
+
165
+ ```tsx
166
+ const access = defineAction({
167
+ id: 'users.access',
168
+ title: 'users.title',
169
+ enabled: false,
170
+ unavailable: { messageKey: 'users.unavailable' },
171
+ });
172
+ // Supply once as a plugin contribution to the shared host list.
173
+ <ActionBoundary action="users.access">
174
+ <UserPage />
175
+ </ActionBoundary>;
176
+ ```
177
+
178
+ A disabled boundary uses the action's localized unavailable message by default. A custom `fallback` may be content or `(message) => ReactNode`. Unknown actions remain blocked. Core treats metadata as opaque; React rendering belongs to `@bitakit/ui`.
179
+
180
+ ## Discovery and explicit composition
181
+
182
+ `@bitakit/core/discovery` is a Node-only build entry point. It scans files and emits imports; the browser provider never reads the filesystem. Adapters call `generateFoundation(root)` initially and `watchFoundation(root)` during development. Next integration is a separate package. Production changes require rebuilding and deployment.
183
+
184
+ The generated config and the optional `FoundationProvider` props `actions`, `plugins`, `interceptors`, and `providers` follow one selection rule:
185
+
186
+ - Omitted: inherit the generated configuration.
187
+ - Explicit array: replace that domain.
188
+ - Empty array: select none.
189
+
190
+ An explicit `actions` array replaces all declarative Actions, including selected plugins' Action contributions. Those plugins' services and setup still run; imperative registrations made by setup or the public API remain explicitly owned by their caller. A setup that requires an excluded Action must be adjusted as well. `plugins=[]` excludes plugins but retains independent app Actions.
191
+
192
+ ```tsx
193
+ // Pseudocode: keep configuration and these arrays stable across renders.
194
+ <FoundationProvider
195
+ config={discovered}
196
+ interceptors={[confirmation, audit]}
197
+ providers={[theme, widgets]}
198
+ ui={ui}
199
+ translate={translate}
200
+ labels={labels}
201
+ >
202
+ <App />
203
+ </FoundationProvider>
204
+ ```
205
+
206
+ Interceptors execute in ascending `order`, preserving registration order for ties. App discovery activates discovered interceptors by default; an explicit `enabled` list selects them (an empty list disables them). Plugin interceptors are local unless marked `scope: 'global'`; host interceptors remain global by default. React providers still require an explicit ordered `enabled` list. The shared file grammar accepts flat, directory and legacy suffix forms. Direct interceptor instances and `defineInterceptor({ requires, create })` factories are supported. The Foundation owns only its registrations; manually installed low-level ActionProvider interceptors are independent and are not removed by a Foundation override.
207
+
208
+ React providers use `defineProvider({ id, component, requires })`. The first entry wraps the others. Required providers must appear earlier; duplicate IDs and missing or reversed dependencies fail before mounting. These wrappers live inside the Foundation context, including its dialog host. They do not replace the host's root authentication or Settings providers.
209
+
210
+ Host services supplied through `services` retain host ownership. Plugin-created services and interceptor registrations are cleaned up with the runtime. Keep service objects and explicit arrays stable; replacing their identity deliberately replaces the runtime composition. Translation changes alone preserve the ActionList, mounted services and pending actions.
211
+
212
+ `actionOverrides` can cap an Action's `enabled` or `visible` state by final ID. A false cap cannot be bypassed by a reactive subscription; true does not bypass business guards or permissions. This affects UI availability, not server authorization.
213
+
214
+ ## Direct Action exports
215
+
216
+ An Action file can default-export an `Action` subclass directly. No registration wrapper or separate factory builder is required. The runtime constructs a fresh instance per runtime, reads its metadata, translates its title and owns its connection lifetime. Its explicit ID wins over the inferred file ID.
217
+
218
+ ```ts
219
+ export default class Logout extends Action {
220
+ constructor() {
221
+ super({ title: 'Nav.logout' });
222
+ }
223
+ async execute() {
224
+ await logout();
225
+ }
226
+ }
227
+ ```
228
+
229
+ For Action dependencies, export a function receiving the typed `ActionEnvironment` (`services`, `translate`, `config`) and returning an Action. The same context is passed to class constructors that need it. Constructors/functions should only create instances; put subscriptions in `connect()` so the ActionList owns cleanup. Discovery does not execute these exports. Plain, form and dialog definitions remain supported. Do not export mutable singleton Action instances.
230
+
231
+ `execute(input, context)` receives the invocation context as its second argument, and its return value becomes the completed result's `value`. A class may declare `success` and `failure` feedback fields; they run through the same translated feedback pipeline as declarative definitions. Without them, class actions keep raw errors and stay silent, so navigation and setting bindings never toast by accident.
232
+
233
+ ## Runtime structure
234
+
235
+ Every contribution kind (plain command, form, dialog, class export) is normalized by an adapter in `src/contributions` into registrations plus the services it requires or watches. The runtime only orders plugins, creates services, registers the adapted entries, subscribes to watched services and re-translates registrations on locale changes. Add a new contribution kind by adding an adapter, not by extending the mount sequence.
236
+
237
+ ## Integration contributions
238
+
239
+ Optional integrations add declarative contribution kinds without teaching Core their meaning. A
240
+ module lists values under `contributions: { [kind]: values }`; exactly one module claims each kind
241
+ with `installs: { [kind]: (values, { module, app, services }) => cleanup }`. During mount the
242
+ runtime installs contributions after services, translation and interceptors and before actions and
243
+ setup, kind by kind in module dependency order. The cleanup belongs to the contributing module's
244
+ scope. A contributed kind without an installer, or a kind claimed twice, fails the mount.
245
+ Integrations type their kinds by augmenting `ContributionMap`.
246
+
247
+ `runtime.contributionsOf(kind)` returns the same values in install order without mounting, so a UI
248
+ integration can prepare an initial render snapshot that equals the mounted state.
249
+ `scopeModule(scope)` identifies the module of a runtime-issued `PluginScope` (the scope passed to
250
+ `setup`); integrations use it to derive ownership instead of trusting caller-supplied owner strings.
251
+
252
+ Discovery supports integration kinds in `foundation.config.ts`:
253
+
254
+ ```ts
255
+ export default defineFoundation({
256
+ kinds: [
257
+ {
258
+ name: 'settings.renderers',
259
+ directory: 'renderers',
260
+ from: '@bitakit/app-preferences/foundation',
261
+ normalize: 'discoverSettingsRenderers',
262
+ },
263
+ ],
264
+ });
265
+ ```
266
+
267
+ Each kind names the folder that identifies it inside every module root and the normalizer to
268
+ import. Generation emits `contributions: { 'settings.renderers': normalize([files], moduleId) }` for
269
+ the app and each enabled plugin; it never executes the files. Folders cannot collide with built-in
270
+ kinds or each other, and a plugin manifest can override a kind's folder through `entries`.
271
+
272
+ ## Provider plugins and typed services
273
+
274
+ Provider adapters live in separate packages: `@bitakit/better-auth` and
275
+ `@bitakit/next-intl`. They return ordinary plugins. Pass them through `plugins`;
276
+ there is no separate integration lifecycle or configuration list. Core has no vendor imports.
277
+ Plugins may contribute services and ordered providers as well as actions, pages and views.
278
+ Use `serviceKey<T>`, `provideService` and `getService` to preserve input/output types without
279
+ pretending that an optional provider is always installed. See the owning integration package README for its setup.
280
+
281
+ Plain Actions can declare `watch: ['auth']` and derive contextual presentation with `resolve(input, { services })`. The runtime validates the observable service, subscribes once per service (even for multiple Actions), refreshes the shared ActionList on changes and owns cleanup. There is no copied session state and no Action-level subscription boilerplate. `requires` remains useful for non-observable dependencies.
282
+
283
+ ### UI styles
284
+
285
+ Core ships no UI stylesheet. React bindings and visual package styles belong to their respective packages.
286
+
287
+ Core has no React dependencies or renderer source files. Presentation values are opaque host extension types. The backend runtime does not require the UI package. See the headless-boundary regression test.
288
+
289
+ ## Typed custom Action state
290
+
291
+ ```ts
292
+ // src/plugins/documents/actions/save.ts
293
+ export default defineAction<{ title: string }>()({
294
+ initialState: { savedCount: 0, lastTitle: '' },
295
+ async execute(input) {
296
+ const document = await this.app.services.documents.save(input.title);
297
+ this.state.update((current) => ({
298
+ savedCount: current.savedCount + 1,
299
+ lastTitle: document.title,
300
+ }));
301
+ return document;
302
+ },
303
+ });
304
+ ```
305
+
306
+ Use method syntax for execute; arrow functions do not receive the bound `this`.
307
+ Input is explicit; state and result types are inferred and included in discovery's ActionMap.
308
+ The original defineAction({...}) context-based API remains available. Keep definitions in
309
+ contribution files and consumers in their own modules. A same-module app lookup preceding
310
+ its own inferred definition can cause a TypeScript augmentation cycle, including with the
311
+ original API; avoid that self-reference or supply an explicit definition type.
312
+
313
+ `this.app`, `this.services` and `this.config` use the existing execution context.
314
+ `this.state.get()` reads current state; `this.state.update(updater)` publishes through the
315
+ existing ActionList. State starts as a structured clone of initialState for each registration;
316
+ use cloneable values and immutable updates. It is shared by bindings to that registration,
317
+ not persisted across unregistration or reload. Input and return values are not stored as state.
318
+ Late updates from a removed or replaced registration return false.
319
+
320
+ Core exports ActionStatus.Idle, Pending, Succeeded and Failed. Snapshots expose status and
321
+ error; the executor owns both. The existing pending guard prevents concurrent execution of
322
+ the same registration. Skipped calls preserve the previous status/error (an intercepted call
323
+ may temporarily enter Pending). ExecutionResult retains its completed/skipped contract, and
324
+ failed executions still reject. A successful retry clears the error.
325
+
326
+ Source responsibilities: actions/state.ts owns lifecycle names and mapped state types;
327
+ contributions/stateful-action.ts adapts instance-style authoring. ActionList remains the sole
328
+ snapshot store, and actions/execution.ts owns lifecycle transitions.
329
+
330
+ ## Mixed interceptor files
331
+
332
+ Both interceptor kinds share `interceptors/`. Subfolders and dotted filenames organize entries;
333
+ the helper's discriminator decides the kind. Default-export a single definition, a named object
334
+ collection, or an array (including collections containing arrays).
335
+
336
+ ```ts
337
+ // src/plugins/documents/interceptors/logging.ts
338
+ import { defineActionInterceptor, defineServiceInterceptor } from '@bitakit/core';
339
+
340
+ export default [
341
+ defineActionInterceptor({
342
+ before() {
343
+ console.log('Action started');
344
+ },
345
+ }),
346
+ defineServiceInterceptor({
347
+ service: 'documents',
348
+ method: 'save',
349
+ before({ args }) {
350
+ console.log(args[0]);
351
+ },
352
+ after({ result }) {
353
+ console.log(result.title);
354
+ },
355
+ onError({ error }) {
356
+ console.error(error);
357
+ },
358
+ }),
359
+ ];
360
+ ```
361
+
362
+ Omit `method` to observe all public string-named methods of the selected service. Service names
363
+ resolve through public service aliases or raw container keys. Known service methods infer argument
364
+ and awaited result types. Action interceptors retain existing plugin/global scope and cancellation;
365
+ `defineInterceptor` remains the legacy Action helper. Service observers explicitly target a service,
366
+ independently of the organizing folder. `order` sorts observers ascending with stable ties.
367
+
368
+ Service hooks are observation-only. Return values are ignored, callback failures are isolated, and
369
+ callbacks are not awaited. Do not mutate observed arguments or results. Business methods retain
370
+ synchronous return behavior, original Promises and original errors. The wrapper binds methods and
371
+ getters to their original instance, preserving private fields. Internal self-calls and calls through
372
+ an original reference outside the container bypass observation. Symbol methods and constructors
373
+ are not observed. The method facade supports ordinary object/class services, including frozen
374
+ objects; it is not a general-purpose transparent reflection or callable-function proxy.
375
+
376
+ Every container consumer, including dependent service factories and Actions, sees the same wrapped
377
+ instance. Disposal disables callbacks, including settlement of an already-running call, and still
378
+ cleans up the original service instance. No second service registry is introduced.
379
+
380
+ Source responsibilities: `interceptors/service.ts` contains definitions and inferred contracts;
381
+ `interceptors/service-observers.ts` wraps method access. `services.ts` owns construction/disposal,
382
+ and runtime routes Action definitions to the existing Action interception pipeline.
383
+
384
+ ### Declarative keyboard metadata
385
+
386
+ `shortcut: { keys: 'Mod+Shift+S' }` declares a keyboard binding without DOM or vendor imports in Core.
387
+ Commands with a required typed input must supply `shortcut.input` of that type; the adapter never
388
+ infers input from focused controls or a last-clicked row. Class Actions, commands and form/dialog
389
+ openers retain this metadata. Internal form-submit registrations are excluded. Browser handling
390
+ belongs to UI's existing ActionProvider; see its README for scopes and collision behavior.
391
+
392
+ ## Navigation boundary
393
+
394
+ Core does not access browser globals for navigation. Mount an ActionList with an explicit
395
+ navigation callback when executing URL Actions outside the UI provider. Without a navigation
396
+ host, URL execution reports an error. The UI ActionProvider supplies browser navigation by
397
+ default; the optional Next and TanStack providers use the application's existing router.
398
+
399
+ ## Runtime events and action setup
400
+
401
+ See [Events and action setup](events.md) for the built-in runtime-local event bus,
402
+ `defineAction({ setup })`, scoped `events.watch`, payload typing and async semantics.
403
+ Existing definition-level `watch: ['serviceId']` and `resolve` retain their service
404
+ observation and execution-time presentation behavior.
@@ -0,0 +1,88 @@
1
+ # Build your first To-do plugin
2
+
3
+ Create three tasks, list them, and delete one. This example shows how separate
4
+ **actions** share one **service**, grouped by a **plugin**. No UI or database is needed.
5
+
6
+ ## Run the complete example
7
+
8
+ Use Node.js 24 in a new folder:
9
+
10
+ ```sh
11
+ npm init -y
12
+ npm install @bitakit/core
13
+ ```
14
+
15
+ Download or copy [todos.mjs](../examples/todos.mjs) and the entire
16
+ [todos folder](../examples/todos), preserving their relative paths. The walkthrough
17
+ uses explicit imports; these files do not require a discovery-enabled host.
18
+
19
+ ```text
20
+ my-example/
21
+ ├── package.json
22
+ ├── todos.mjs
23
+ └── todos/
24
+ ├── plugin.mjs
25
+ ├── services/
26
+ │ └── tasks.mjs
27
+ └── actions/
28
+ ├── create.mjs
29
+ ├── list.mjs
30
+ └── delete.mjs
31
+ ```
32
+
33
+ Run `node todos.mjs`. The first result contains three tasks. The second contains
34
+ only tasks 1 and 3, because the script deleted task 2. Each action execution returns
35
+ an outcome; successful execution has `status: 'completed'` and its result in `value`.
36
+
37
+ ## The service owns the task behavior
38
+
39
+ [The task service](../examples/todos/services/tasks.mjs) stores tasks in an array and
40
+ exposes `create(title)`, `list()`, and `delete(id)`. Its factory runs when Core mounts
41
+ the runtime. IDs increase independently of list length, so deletion does not cause
42
+ ID reuse. This is temporary memory, not database persistence.
43
+
44
+ ## Three actions, one service
45
+
46
+ | Action | Input | Service operation | Successful result |
47
+ | ---------------------------------------------------- | ---------- | ----------------- | -------------------------- |
48
+ | [todos.create](../examples/todos/actions/create.mjs) | Task title | `create(title)` | Created task |
49
+ | [todos.list](../examples/todos/actions/list.mjs) | None | `list()` | Current tasks |
50
+ | [todos.delete](../examples/todos/actions/delete.mjs) | Task ID | `delete(id)` | Whether a task was removed |
51
+
52
+ Each action declares `requires: ['todos']`. The action context supplies the service
53
+ and the caller's `input`. The plugin imports these definitions and contributes them
54
+ to the same runtime; they do not create separate service instances.
55
+
56
+ ```text
57
+ create action ──┐
58
+ list action ──┼──▶ task service ──▶ shared in-memory tasks
59
+ delete action ──┘
60
+ ```
61
+
62
+ The workspace version also emits `todos.changed` after mutations. The delete action
63
+ declares `events` and `onEvent`, checks its initial state in `setup`,
64
+ and disables itself when the list becomes empty. Core removes this subscription
65
+ when the action registration ends. This addition is not in published Core 0.1.0 yet.
66
+
67
+ Deleting a task removes data. It does not unregister the delete action itself.
68
+ Listing tasks is shown as an action to demonstrate the shared execution path;
69
+ application code can also call a service directly when no action behavior is needed.
70
+
71
+ ## The application composes and runs the plugin
72
+
73
+ [The entry script](../examples/todos.mjs) creates one ActionList and runtime, mounts
74
+ the plugin, executes the scenario, and calls cleanup in a `finally` block. Core
75
+ coordinates lifecycle; your application decides which operations to invoke.
76
+
77
+ These JavaScript examples demonstrate runtime behavior. For typed action inputs,
78
+ use TypeScript definitions and the documented generated or explicit action contracts.
79
+ A real app also validates untrusted input and enforces permissions on the server.
80
+
81
+ ## Add UI or persistence later
82
+
83
+ Keep task operations in the service. A UI can bind to the named actions through the
84
+ React package; a storage implementation can replace the in-memory behavior. Neither
85
+ is automatically created by this example.
86
+
87
+ See [Core introduction](../README.md), [Core reference](reference.md), and
88
+ [file discovery conventions](file-contributions.md) for the next steps.
@@ -0,0 +1,7 @@
1
+ import { defineAction } from '@bitakit/core';
2
+
3
+ export default defineAction({
4
+ id: 'todos.create',
5
+ requires: ['todos'],
6
+ execute: ({ services, input }) => services.todos.create(input),
7
+ });
@@ -0,0 +1,14 @@
1
+ import { defineAction } from '@bitakit/core';
2
+
3
+ export default defineAction({
4
+ id: 'todos.delete',
5
+ requires: ['todos'],
6
+ events: ['todos.changed'],
7
+ setup({ services, action }) {
8
+ action.enabled = services.todos.list().length > 0;
9
+ },
10
+ onEvent(_event, { services, action }) {
11
+ action.enabled = services.todos.list().length > 0;
12
+ },
13
+ execute: ({ services, input }) => services.todos.delete(input),
14
+ });
@@ -0,0 +1,7 @@
1
+ import { defineAction } from '@bitakit/core';
2
+
3
+ export default defineAction({
4
+ id: 'todos.list',
5
+ requires: ['todos'],
6
+ execute: ({ services }) => services.todos.list(),
7
+ });
@@ -0,0 +1,11 @@
1
+ import { definePlugin } from '@bitakit/core';
2
+ import tasks from './services/tasks.mjs';
3
+ import create from './actions/create.mjs';
4
+ import list from './actions/list.mjs';
5
+ import remove from './actions/delete.mjs';
6
+
7
+ export default definePlugin({
8
+ id: 'todos',
9
+ services: [tasks],
10
+ actions: [create, list, remove],
11
+ });
@@ -0,0 +1,30 @@
1
+ import { defineService } from '@bitakit/core';
2
+
3
+ function createTodoService({ events }) {
4
+ let tasks = [];
5
+ let nextId = 1;
6
+
7
+ function create(title) {
8
+ const task = { id: nextId++, title, done: false };
9
+ tasks.push(task);
10
+ events.emit('todos.changed', { kind: 'added', id: task.id });
11
+ return task;
12
+ }
13
+
14
+ return {
15
+ create,
16
+ list: () => [...tasks],
17
+ delete(id) {
18
+ const previousCount = tasks.length;
19
+ tasks = tasks.filter((task) => task.id !== id);
20
+ const removed = tasks.length < previousCount;
21
+ if (removed) events.emit('todos.changed', { kind: 'removed', id });
22
+ return removed;
23
+ },
24
+ };
25
+ }
26
+
27
+ export default defineService({
28
+ id: 'todos',
29
+ create: createTodoService,
30
+ });
@@ -0,0 +1,17 @@
1
+ import { createActionList, FoundationRuntime } from '@bitakit/core';
2
+ import todos from './todos/plugin.mjs';
3
+
4
+ const actions = createActionList();
5
+ const runtime = new FoundationRuntime(actions, { plugins: [todos] });
6
+ const stop = runtime.mount();
7
+
8
+ try {
9
+ await actions.execute('todos.create', 'Learn plugins');
10
+ await actions.execute('todos.create', 'Connect a service');
11
+ await actions.execute('todos.create', 'Try actions');
12
+ console.log('Before:', await actions.execute('todos.list'));
13
+ await actions.execute('todos.delete', 2);
14
+ console.log('After:', await actions.execute('todos.list'));
15
+ } finally {
16
+ stop();
17
+ }
package/package.json CHANGED
@@ -1,13 +1,15 @@
1
1
  {
2
2
  "name": "@bitakit/core",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "files": [
7
7
  "dist",
8
8
  "README.md",
9
9
  "discovery",
10
- "docs"
10
+ "docs",
11
+ "examples",
12
+ "assets"
11
13
  ],
12
14
  "exports": {
13
15
  ".": {
@@ -31,11 +33,12 @@
31
33
  },
32
34
  "dependencies": {
33
35
  "jiti": "^2.7.0",
36
+ "mitt": "^3.0.1",
34
37
  "typescript": "^5.9.3",
35
38
  "zustand": "^5.0.0"
36
39
  },
37
40
  "devDependencies": {},
38
- "description": "Framework-independent Foundation runtime, actions, and typed services.",
41
+ "description": "AI-friendly, type-safe building blocks for modular apps: plugins, services, actions, and events.",
39
42
  "license": "MIT",
40
43
  "repository": {
41
44
  "type": "git",