@cratis/pi 7.136.0 → 7.137.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.
Files changed (32) hide show
  1. package/package/corpus/harnesses/copilot/instructions/profiles.instructions.md +11 -7
  2. package/package/corpus/product-sync.json +9 -6
  3. package/package/corpus/rules/issue-assignment.md +2 -0
  4. package/package/corpus/rules/profiles.md +11 -7
  5. package/package/corpus/skills/cratis-arc-code-analysis-typescript/SKILL.md +96 -0
  6. package/package/corpus/skills/cratis-arc-command-typescript/SKILL.md +22 -13
  7. package/package/corpus/skills/cratis-arc-command-typescript/references/chronicle-events.md +5 -5
  8. package/package/corpus/skills/cratis-arc-command-typescript/references/command-operations.md +1 -1
  9. package/package/corpus/skills/cratis-arc-command-typescript/references/command-pipeline.md +137 -0
  10. package/package/corpus/skills/cratis-arc-command-typescript/references/configuration.md +83 -0
  11. package/package/corpus/skills/cratis-arc-command-typescript/references/hosting-and-storage.md +5 -4
  12. package/package/corpus/skills/cratis-arc-command-typescript/references/identity-and-introspection.md +1 -3
  13. package/package/corpus/skills/cratis-arc-command-typescript/references/observability-and-host-scopes.md +1 -1
  14. package/package/corpus/skills/cratis-arc-command-typescript/references/project-setup.md +14 -9
  15. package/package/corpus/skills/cratis-arc-command-typescript/references/proxy-generation.md +2 -2
  16. package/package/corpus/skills/cratis-arc-command-typescript/references/proxy-generator-options.md +90 -0
  17. package/package/corpus/skills/cratis-arc-command-typescript/verification.json +2 -2
  18. package/package/corpus/skills/cratis-arc-query-typescript/SKILL.md +4 -2
  19. package/package/corpus/skills/cratis-arc-query-typescript/references/product-sources.md +1 -2
  20. package/package/corpus/skills/cratis-arc-query-typescript/references/query-pipeline.md +125 -0
  21. package/package/corpus/skills/cratis-arc-query-typescript/references/storage-observation-and-compliance.md +1 -1
  22. package/package/corpus/skills/cratis-arc-query-typescript/verification.json +1 -1
  23. package/package/corpus/skills/cratis-arc-storage-typescript/SKILL.md +150 -0
  24. package/package/corpus/skills/cratis-arc-tenancy-typescript/LICENSE +2 -0
  25. package/package/corpus/skills/cratis-arc-tenancy-typescript/SKILL.md +125 -0
  26. package/package/corpus/skills/cratis-arc-testing-typescript/SKILL.md +153 -0
  27. package/package/corpus/skills/cratis-arc-validation-typescript/SKILL.md +3 -4
  28. package/package/corpus/skills/cratis-arc-validation-typescript/verification.json +1 -1
  29. package/package/corpus/skills/cratis-engineering-issue-design-note/SKILL.md +2 -1
  30. package/package/corpus/skills/cratis-engineering-issue-hygiene/SKILL.md +5 -2
  31. package/package/profile-catalog.json +5 -1
  32. package/package.json +1 -1
@@ -1,10 +1,10 @@
1
1
  ## Generate metadata and proxies
2
2
 
3
- Source: `Cratis/Arc.TypeScript` (source preview):
3
+ Source: `Cratis/Arc.TypeScript`:
4
4
  `Source/Tools/ProxyGenerator/parseSourceOptions.ts`,
5
5
  `Documentation/proxy-generation/getting-started.md`, and sample generator scripts.
6
6
 
7
- `arc-proxygenerator` (package `@cratis/arc.proxygenerator`, also unpublished)
7
+ `arc-proxygenerator` (package `@cratis/arc.proxygenerator`)
8
8
  reads the TypeScript source with the compiler API — it never queries a running
9
9
  server. It writes server metadata and client proxies in one run. The CLI
10
10
  rejects relative paths, and the output folder must exist:
@@ -0,0 +1,90 @@
1
+ <!-- Copyright (c) Cratis. All rights reserved. -->
2
+ <!-- Licensed under the MIT license. See LICENSE file in the project root for full license information. -->
3
+
4
+ # `arc-proxygenerator` options, types and ownership
5
+
6
+ Source: `Cratis/Arc.TypeScript`: `Source/Tools/ProxyGenerator/parseSourceOptions.ts`,
7
+ `Documentation/proxy-generation/{configuration,type-mapping,validation,file-index-tracking,low-level-manifest}.md`.
8
+ The CLI reads source with the compiler API; it never calls a running server.
9
+ Options accept `--option value` and `--option=value`; a missing or empty value
10
+ is rejected; `--help` prints usage. The scaffold script is in `proxy-generation.md`.
11
+
12
+ ## Required
13
+
14
+ | Option | Meaning |
15
+ | --- | --- |
16
+ | `--project <tsconfig>` | `tsconfig.json` of the project declaring the artifacts (absolute path) |
17
+ | `--artifacts <folder>` | Discovery root; only exported classes below it count; use the folder given to `discover()` |
18
+ | `--output <folder>` | Existing directory; equal to or containing the artifacts root means co-located output |
19
+
20
+ ## Route alignment (must match the server)
21
+
22
+ | Option | Default | Server equivalent |
23
+ | --- | --- | --- |
24
+ | `--root-namespace <ns>` | none | `discover(folder, { rootNamespace })`; also prefixes generated model folders |
25
+ | `--segments-to-skip <n>` | `0` | `generatedApis.segmentsToSkipForRoute` |
26
+ | `--api-prefix <prefix>` | `api` | `generatedApis.routePrefix` |
27
+ | `--skip-command-name-in-route` | off | `includeCommandNameInRoute: false` |
28
+ | `--skip-query-name-in-route` | off | `includeQueryNameInRoute: false` |
29
+
30
+ `--root-namespace App` writes models under `App/...`; after upgrading, the
31
+ generator removes the old unprefixed files it owns.
32
+
33
+ ## Output and behavior
34
+
35
+ | Option | Effect |
36
+ | --- | --- |
37
+ | `--use-proxy-file-suffix` | Name files `*.proxy.ts`; required for co-located output |
38
+ | `--js-import-specifiers` | `.js` extensions in local imports for native Node ESM; leave off for Vite and bundlers |
39
+ | `--emit-interfaces` | Interfaces instead of model classes; loses decorated model hydration |
40
+ | `--skip-react-hooks` | Server-only proxies: no `@cratis/arc.react` import and no `use*`/`when` hooks |
41
+ | `--scalar-concept-subclasses` | Type indirect and generic concept subclasses as their underlying value |
42
+ | `--skip-index-generation` | No `index.ts` barrels (automatic when co-located) |
43
+ | `--skip-output-deletion` | Keep stale generated files |
44
+ | `--metadata <file>` | Write server artifact metadata (absolute path) and infer undecorated bindings |
45
+ | `--use-generated-metadata` | Infer the same bindings for client-only generation |
46
+ | `--check-metadata` | Read-only: fail when the `--metadata` module no longer matches source |
47
+ | `--type-mapping <Type>=<package>[#<export>]` | Import a type from another package instead of generating it; repeatable |
48
+ | `--watch`, `--watch-poll-interval <ms>` | Regenerate on edits; poll default 1000 on macOS, 5000 elsewhere, `0` disables |
49
+
50
+ ## What the generator recognizes
51
+
52
+ | Server declaration | Client type |
53
+ | --- | --- |
54
+ | `String`, `Number`, `Boolean`, `Date` | `string`, `number`, `boolean`, `Date` |
55
+ | Fundamentals `Guid`, `DateOnly`, `TimeOnly`, `TimeSpan` | the same Fundamentals types |
56
+ | `ConceptAs<T>` | its underlying type (`TaskId extends ConceptAs<Guid>` becomes `Guid`) |
57
+ | Decorated models | generated classes (or interfaces) |
58
+ | Arrays, string/number enums, string-literal unions | arrays, enums, unions |
59
+ | `@derivedType('id')` classes and their bases | emitted with the same declaration |
60
+
61
+ Discovery skips `index.ts`, `given/`, `dist/`, `node_modules/`, `for_*/` and
62
+ symbolic links. Unsupported shapes fail with a source diagnostic, not silently.
63
+
64
+ ## Client validators
65
+
66
+ The generator copies literal, unconditional `ruleFor` chains from the
67
+ constructors of `@validator(Target)` classes into generated validators, for
68
+ commands and for queries that declare an explicit `argumentsModel`. Client-safe
69
+ rules: `notNull`, `notEmpty`, `minLength`, `maxLength`, `length`,
70
+ `emailAddress`, `phone`, `url`, `matches`, `greaterThan`,
71
+ `greaterThanOrEqual`, `lessThan`, `lessThanOrEqual`, with messages. `when`,
72
+ `unless`, `must`, `mustAsync` and anything needing runtime evaluation stay on
73
+ the server and produce a diagnostic. The server validates every request anyway.
74
+
75
+ ## Ownership of files
76
+
77
+ Every generated file starts with `// @generated by Cratis. Source: ... Hash: ...`.
78
+ Never edit such a file; the next run replaces it. The generator removes only
79
+ files carrying its header and never touches hand-written files, so a hand-written
80
+ file at a generated path is a conflict to resolve, not something to overwrite.
81
+
82
+ ## Low-level definitions
83
+
84
+ `defineCommand`/`defineQuery` have Zod schemas, so the analyzer cannot see their
85
+ output types. Declare `clientOutput: { output }` on each definition, write a
86
+ version 1 JSON manifest with `exportClientManifest(server)` from
87
+ `@cratis/arc.core`, then run the older positional CLI form with absolute paths:
88
+ `arc-proxygenerator <manifest.json> <output-folder>`. That form reads JSON only
89
+ and never imports the application; export does not call handlers, validators or
90
+ authorization callbacks.
@@ -3,7 +3,7 @@
3
3
  "input": "Add a command that registers an author to an Arc for TypeScript server and append an event to Chronicle.",
4
4
  "fixtures": [],
5
5
  "assertions": [
6
- { "kind": "skill-contains", "value": "**None of the server packages is published to npm.**" },
6
+ { "kind": "skill-contains", "value": "**The server packages are published to npm at stable 1.0.0.**" },
7
7
  { "kind": "skill-contains", "value": "**`@cratis/arc` is a different package.**" },
8
8
  { "kind": "skill-contains", "value": "ArcApplication.createBuilder()" },
9
9
  { "kind": "skill-contains", "value": "**No key is inferred from an unmarked `id`\nfield.**" },
@@ -11,7 +11,7 @@
11
11
  { "kind": "skill-contains", "value": "is created through its **constructor** in `handle()`" },
12
12
  { "kind": "skill-contains", "value": "`--check-metadata`" },
13
13
  { "kind": "skill-contains", "value": "CommandScenario.for(RegisterTask, RegisterTaskValidator)", "file": "references/command-specifications.md" },
14
- { "kind": "skill-contains", "value": "(source preview)" },
14
+ { "kind": "skill-contains", "value": "npm install" },
15
15
  { "kind": "skill-contains", "value": "peer `^6.29.0`" },
16
16
  { "kind": "skill-contains", "value": "Outside **Development**" },
17
17
  { "kind": "skill-contains", "value": "not identity\n discovery", "file": "references/identity-and-introspection.md" },
@@ -11,8 +11,8 @@ In Arc for TypeScript a read model is a decorated class, and its reads are
11
11
  the arguments, resolves services, pages and sorts, and wraps every answer in the
12
12
  same `QueryResult` envelope. There is no controller to write.
13
13
 
14
- Arc for TypeScript is a **source preview**: `@cratis/arc.core` and the other
15
- server packages are not published to npm, and the API may change. `@cratis/arc`
14
+ Arc for TypeScript ships as stable 1.0.0 packages on npm (`@cratis/arc.core`
15
+ and the other server packages). `@cratis/arc`
16
16
  is the separate, published **client** that generated query proxies import in a
17
17
  frontend. Project setup, the builder, and hosts are in
18
18
  `cratis-arc-command-typescript`.
@@ -227,6 +227,8 @@ false`).
227
227
  opens. A revoked role does not close it; add an observable emission guard when
228
228
  access must be re-checked while the stream runs.
229
229
 
230
+ Read [references/query-pipeline.md](references/query-pipeline.md) for global query filters, renderers, read-model interceptors, read consistency, hubs and query health.
231
+
230
232
  ## Serve stored read models
231
233
 
232
234
  The storage integrations register tenant-scoped service tokens; a query never
@@ -2,8 +2,7 @@
2
2
 
3
3
  This reference holds the source material behind the query guidance.
4
4
 
5
- Source: `Cratis/Arc.TypeScript` (source preview;
6
- server packages not on npm), reading
5
+ Source: `Cratis/Arc.TypeScript`, reading
7
6
  `Source/Core/queries/index.ts`, `Documentation/queries/**`,
8
7
  `Documentation/mongodb/**`, `Documentation/sql/**`,
9
8
  `Documentation/testing/queries.md` and `observable-queries.md`, and
@@ -0,0 +1,125 @@
1
+ <!-- Copyright (c) Cratis. All rights reserved. -->
2
+ <!-- Licensed under the MIT license. See LICENSE file in the project root for full license information. -->
3
+
4
+ # Query pipeline, filters, renderers, interceptors and hubs
5
+
6
+ ## Contents
7
+
8
+ - Order of stages
9
+ - Global query filters
10
+ - Renderers (provider-owned results)
11
+ - Read-model interceptors (one shaping rule for every query)
12
+ - Read consistency with Chronicle
13
+ - Hubs and health
14
+
15
+ Source: `Cratis/Arc.TypeScript`: `Documentation/queries/{query-pipeline,query-filters,renderers,read-model-interception,read-consistency,query-health,observable-query-demultiplexer}.md`,
16
+ `Source/Core/queries/index.ts`. Use this when a query must be gated for every
17
+ caller, reshaped before it leaves the server, or served by a provider that pages
18
+ itself.
19
+
20
+ ## Order of stages
21
+
22
+ | Step | Configured with | Failure |
23
+ | --- | --- | --- |
24
+ | 1 Authentication | `authentication` handlers or native principal | 401 |
25
+ | 2 Tenant | `tenancy` | 400 or 403 when required |
26
+ | 3 Read arguments | query string for GET, JSON body for `QUERY` | 400 `malformedRequest` |
27
+ | 4 Declared authorization | `@roles`, `@authorize`, `@allowAnonymous` | 403 |
28
+ | 5 Bind arguments | `argument(...)` descriptors or a Zod `schema` | 400 `malformedRequest` |
29
+ | 6 Per-request authorization | `authorize(input, context)` on low-level definitions | 403 |
30
+ | 7 Global authorization filters | scoped `AuthorizationQueryFilter` services | 403; a throwing filter fails closed with 500 |
31
+ | 8 Global ordinary filters | scoped `QueryPipelineFilter` services | 400 validation, 500 exception |
32
+ | 9 Validation | `QueryValidator`, concept validators | 400 with every result |
33
+ | 10 Perform | the query method | 500 when it throws |
34
+
35
+ Result stages then run in the same scope: **renderer** (first whose `canRender`
36
+ accepts the value), **read-model interceptors** (exact runtime class), sorting
37
+ and paging (in memory for arrays; a `queryPage` is used as is), encoding. For
38
+ an observable query the guard stages run **once** when the subscription opens;
39
+ result stages run for the snapshot and **every** emission. Emission-time access
40
+ needs an emission guard (see `cratis-arc-command-typescript`,
41
+ `identity-and-introspection.md`).
42
+
43
+ ## Global query filters
44
+
45
+ `AuthorizationQueryFilter` runs first, before validator and performer
46
+ dependencies are constructed; `QueryPipelineFilter` follows. Both implement
47
+ `onPerform(context: QueryContext)` and return a `QueryResult` fragment or
48
+ nothing. Helpers: `unauthorizedQueryResult(context)` (403, no reason),
49
+ `queryFilterResult(context, { validationResults })`.
50
+
51
+ ```typescript
52
+ import { authorizationQueryFilter, unauthorizedQueryResult,
53
+ type AuthorizationQueryFilter, type QueryContext, type QueryResult } from '@cratis/arc.core';
54
+
55
+ @authorizationQueryFilter()
56
+ class TenantGate implements AuthorizationQueryFilter {
57
+ onPerform(context: QueryContext): QueryResult | void {
58
+ if (!context.tenantId) return unauthorizedQueryResult(context);
59
+ }
60
+ }
61
+ // builder.add(TenantGate) -- or addAuthorizationQueryFilter(token) / addQueryPipelineFilter(token)
62
+ ```
63
+
64
+ `@queryPipelineFilter()` is the matching decorator for ordinary filters.
65
+ `context` carries the bound `query`, request identity, `options` and an
66
+ `operationName` equal to the declaration identity shown in introspection.
67
+ Order inside each group: `ArcOptions` tokens, explicit builder calls, then
68
+ decorated classes in `add()` order. A token registered twice runs once; a token
69
+ in both groups fails at `build()`. Arc applies `context.allowedSeverity` to each
70
+ fragment before deciding to stop; denial always stops the chain. Filters do not
71
+ run per emission.
72
+
73
+ ## Renderers (provider-owned results)
74
+
75
+ When the method returns a provider query object that counts and pages itself,
76
+ implement `QueryRenderer` with `@queryRenderer()`:
77
+ `canRender(value)` and `render(value, context, options)`, returning data or
78
+ `queryPage(items, totalItems, sorting)` with the provider's authoritative total.
79
+ Register with `builder.add(Renderer)` or `addQueryRenderer(token)`; low-level
80
+ `ArcOptions.queryRenderers`. Only the first accepting renderer runs, and the
81
+ renderer must own sorting and paging itself.
82
+
83
+ ## Read-model interceptors (one shaping rule for every query)
84
+
85
+ ```typescript
86
+ @readModelInterceptor()
87
+ class PublicAccountName implements ReadModelInterceptor<AccountSummary> {
88
+ readonly model = AccountSummary;
89
+ intercept(account: AccountSummary): AccountSummary { /* return a copy */ }
90
+ }
91
+ ```
92
+
93
+ Runs on ordinary results, observable HTTP snapshots and each emission, for the
94
+ top-level result, array items and `queryPage` items. It matches the **exact
95
+ runtime class**, is not applied to deeper nested instances (for example a joined
96
+ `select` result), and a failure fails the query. Return a replacement; never
97
+ mutate a model another subscriber shares. Register with `builder.add` or
98
+ `addReadModelInterceptor(token)`; low-level `ArcOptions.readModelInterceptors`.
99
+
100
+ ## Read consistency with Chronicle
101
+
102
+ A successful append commits events but does not mean an active projection shows
103
+ them yet. Choose per read: default (`models.getById(View, id)`), immediate
104
+ (mark the model-bound projection `@passive` and pass
105
+ `ChronicleReadConsistency.Immediate`), or wait after write
106
+ (`withChronicle({ ..., completionTimeoutMs })`). Chronicle waits for **every**
107
+ observer on the event log, so a lagging unrelated observer makes the wait run
108
+ to the timeout. Details: `cratis-arc-command-typescript`, `chronicle-events.md`.
109
+
110
+ ## Hubs and health
111
+
112
+ One client connection can carry many subscriptions: the WebSocket hub at
113
+ `/.cratis/queries/ws` (plain `@cratis/arc` client default) and the SSE hub at
114
+ `GET /.cratis/queries/sse` with `POST .../subscribe` and `.../unsubscribe`
115
+ (`<Arc>` React provider default). `queryName` is the query's full identity.
116
+ Every subscription is authorized independently. Browser `EventSource` cannot
117
+ set an `Authorization` header, so sign-in for SSE needs the real session
118
+ cookie, not the display-only identity cookie. Control requests must come from
119
+ the caller that opened the connection. Size limits are in
120
+ `cratis-arc-command-typescript`, `configuration.md`.
121
+
122
+ `query: { enableObservableHealth: true }` registers an authenticated,
123
+ caller-scoped `/.cratis/queries/health` observable query. It lists only the
124
+ caller's own tenant and principal hub connections, subscription counts and
125
+ query groups; it is off by default.
@@ -3,7 +3,7 @@
3
3
 
4
4
  # Storage observation and protected raw reads
5
5
 
6
- Source: `Cratis/Arc.TypeScript` (source preview, not on npm):
6
+ Source: `Cratis/Arc.TypeScript`:
7
7
  `Source/Drizzle/DrizzleOptions.ts`, package exports and observation code,
8
8
  `Source/MongoDB/MongoReadModelsOptions.ts`, `Source/Chronicle/releaseRawDocument.ts`,
9
9
  `Documentation/sql/observing-tables.md`, `observing-postgresql.md`, and
@@ -3,7 +3,7 @@
3
3
  "input": "Expose a live list of tasks from an Arc for TypeScript read model.",
4
4
  "fixtures": [],
5
5
  "assertions": [
6
- { "kind": "skill-contains", "value": "is a **source preview**" },
6
+ { "kind": "skill-contains", "value": "ships as stable 1.0.0 packages on npm" },
7
7
  { "kind": "skill-contains", "value": "- the method is `static`," },
8
8
  { "kind": "skill-contains", "value": "**Absence is an answer, not an error.**" },
9
9
  { "kind": "skill-contains", "value": "`@query({ observable: true }, service(Tasks))`" },
@@ -0,0 +1,150 @@
1
+ ---
2
+ name: cratis-arc-storage-typescript
3
+ description: Use when an Arc Node.js server must read or observe read models in MongoDB or a SQL database through Drizzle. Not for Chronicle projections, query method design or the C# EF Core and MongoDB integrations.
4
+ license: MIT
5
+ ---
6
+
7
+ # MongoDB and SQL storage for an Arc Node.js server
8
+
9
+ Two optional packages connect read models to a database. Importing the package
10
+ adds its method to the builder. Both pick the database from the resolved tenant
11
+ (see `cratis-arc-tenancy-typescript`), never from a query argument, and both
12
+ need the model's `@field` declarations.
13
+
14
+ | Package | Builder method | Peer | Use for |
15
+ | --- | --- | --- | --- |
16
+ | `@cratis/arc.mongodb` | `withMongoDB` | `mongodb` `^6.21.0` | documents, change-stream observation |
17
+ | `@cratis/arc.drizzle` | `withDrizzle` | `drizzle-orm` `^0.45.0`, `rxjs` | PostgreSQL, MySQL, SQLite tables |
18
+
19
+ Query methods, argument binding and observable queries are in
20
+ `cratis-arc-query-typescript`; this skill covers the storage side.
21
+
22
+ ## MongoDB
23
+
24
+ ```typescript
25
+ import { field, Guid } from '@cratis/fundamentals';
26
+ import { key, query, queryOptions, readModel, service, type QueryOptions } from '@cratis/arc.core';
27
+ import { mongoCollection, type MongoCollection } from '@cratis/arc.mongodb';
28
+
29
+ export class TaskRecord {
30
+ @field(Guid) @key() id!: Guid;
31
+ @field(String) title!: string;
32
+ }
33
+ const tasks = mongoCollection(TaskRecord);
34
+
35
+ @readModel()
36
+ export class TaskQueries {
37
+ @query(service(tasks), queryOptions())
38
+ static page(items: MongoCollection<TaskRecord>, options: QueryOptions) {
39
+ return items.queryPage({}, options);
40
+ }
41
+ }
42
+ // builder.add(TaskQueries).withMongoDB({ client, database: 'tasks', readModels: [TaskRecord] });
43
+ ```
44
+
45
+ - `@key()` marks the field stored as `_id`; without it a field named `id` is
46
+ used; a model with neither, or with several keys, is rejected. Only `@field`
47
+ properties are read and written.
48
+ - List every injected model in `readModels`. `mongoCollection(Type)` resolves to
49
+ the collection in the current tenant's database.
50
+ - Options: `client` or `server` (URI), `database` (default; other tenants use
51
+ `<database>+<tenantId>`), `databaseNameResolver(tenant, context)`,
52
+ `serverResolver`, `namingPolicy`, `collectionName(model)`,
53
+ `ignoreConventions`, `maxObservableItems` (1000), `maxPageSize` (100, at most
54
+ 10 000). `withMongoDB` also reads `Cratis:MongoDB:{Server,Database}`.
55
+ - Build owner filters from the verified principal
56
+ (`items.find({ owner: principal.id })`), never from a caller-supplied filter.
57
+ - **Naming.** `defaultMongoNamingPolicy` keeps declared property names and
58
+ pluralizes the class name (`TaskRecords`); `camelCaseMongoNamingPolicy`
59
+ camel-cases both. To read documents a .NET service wrote with the default
60
+ policy, spell fields as .NET does (`Title`).
61
+ - **Storage format.** `Guid` is standard UUID binary (subtype 4); a concept is
62
+ its underlying value; `Date` a BSON date; `DateOnly` a date at 12:00 UTC;
63
+ `TimeOnly` a date on 1970-01-01 UTC; `TimeSpan` a string; nested decorated
64
+ models embed; `@derivedType('id')` adds `_derivedTypeId`. No global BSON
65
+ conventions or class maps are installed.
66
+ - **Geospatial.** Declare `@field(Point)` (also `LineString`, `Polygon`) from
67
+ `@cratis/fundamentals/geospatial`; longitude comes first. Stored as GeoJSON;
68
+ creating `2dsphere` indexes and `$near` filters is the application's job.
69
+ - **Paging.** `queryPage(filter, options)` pushes count, sort, skip and limit
70
+ into MongoDB. Only declared fields may sort (an unknown field, including
71
+ `$where`, answers 400); an `_id` tiebreaker keeps order stable.
72
+ - **Observing.** `observe(filter?)` emits full lists, `observeById(id)` one
73
+ document or `null`, `observeIterable(filter?)` an async iterable without RxJS.
74
+ All use change streams, which need a replica set or sharded cluster; a
75
+ standalone server fails before the initial read.
76
+ - **Watcher and joins.** Resolve `mongoDBWatcher` in the same scope as the
77
+ collections: `watcher.changes(books)` streams change events;
78
+ `watcher.observe(books, filter).join(authors, filter).select((a, b) => ...)`
79
+ recomputes a combined result when either changes. Join only collections from
80
+ the same scope. A non-resumable error terminates subscribers; resubscribe,
81
+ because the watcher never silently skips an interval. It is not a durable
82
+ event consumer.
83
+
84
+ ## SQL with Drizzle
85
+
86
+ ```typescript
87
+ import { sqliteTable, text } from 'drizzle-orm/sqlite-core';
88
+ import { DrizzleDialect, drizzleReadModel, guidCodec, sqliteColumn, type DrizzleReadModels } from '@cratis/arc.drizzle';
89
+
90
+ export const tasks = sqliteTable('tasks', {
91
+ id: sqliteColumn(guidCodec(DrizzleDialect.SQLite))('id').primaryKey(),
92
+ title: text('title').notNull()
93
+ });
94
+ export class TaskRecord {
95
+ @field(Guid) @key() id!: Guid;
96
+ @field(String) title!: string;
97
+ }
98
+ @readModel()
99
+ export class TaskQueries {
100
+ @query(service(drizzleReadModel(TaskRecord)), queryOptions())
101
+ static page(rows: DrizzleReadModels<TaskRecord>, options: QueryOptions) {
102
+ return rows.queryPage(undefined, options);
103
+ }
104
+ }
105
+ // builder.add(TaskQueries).withDrizzle({ dialect: DrizzleDialect.SQLite, database,
106
+ // readModels: [{ type: TaskRecord, table: tasks }] });
107
+ ```
108
+
109
+ - Each `@field` needs a column under the **same property key** of the Drizzle
110
+ table object (the SQL column name is yours); the table needs a primary key.
111
+ Registration fails otherwise. Columns not on the model are never selected.
112
+ - Options: `dialect` (`DrizzleDialect.PostgreSQL | MySQL | SQLite`), `database`
113
+ (default tenant only), `databaseFactory(tenant, context)` (sync or async; the
114
+ application caches and disposes), `readModels`, `maxPageSize`, `observation`.
115
+ With neither a factory nor a matching `database`, access fails with
116
+ `A tenant is required for Drizzle access`.
117
+ - **Codecs** map Arc types to columns: `guidCodec(dialect)` (`uuid`, `char(36)`,
118
+ `text`), `conceptCodec(Concept, ConceptCodecKind.String | Number, dialect)`,
119
+ `dateOnlyCodec`, `timeOnlyCodec`, `timeSpanCodec`, `jsonCodec(dialect,
120
+ validate)`, wrapped by `pgColumn`, `mysqlColumn` or `sqliteColumn`. A concept
121
+ class declares `static readonly valueType` because generics are erased.
122
+ - **Schema.** Arc checks table against model at startup and never creates,
123
+ alters or migrates the database. Add the column to the table, the model and a
124
+ migration together (for example a drizzle-kit migration you own).
125
+ - **Writes** go through `drizzleDatabase<TDatabase>()` injected into `handle()`;
126
+ `database.native` is the Drizzle database. `queryPage` pushes count, sort,
127
+ limit and offset into SQL.
128
+ - **Observation is opt-in.** `DrizzleObservation.InProcess` sees only writes
129
+ announced with `database.notifyChanged(table)` in this process.
130
+ `DrizzleObservation.PostgreSQLNotify` sees committed changes from any process:
131
+ install the trigger SQL from `postgresqlChangeTrigger(table, { schema })` in an
132
+ application migration and pass a listener factory returning a **new, dedicated**
133
+ `pg.Client` through `nodePostgresListener` (`pg` `^8`). Arc does not create
134
+ database objects at runtime. NOTIFY is not a durable log: states during a
135
+ disconnect are not replayed. Details in `cratis-arc-query-typescript`,
136
+ `storage-observation-and-compliance.md`.
137
+
138
+ ## Pitfalls
139
+
140
+ - A singleton holding a collection or connection keeps the first tenant; keep
141
+ handles in scoped services or resolve through the tokens.
142
+ - Do not slice arrays in memory to page a database result; use `queryPage`.
143
+ - A read model class used for storage needs `@field` metadata; a missing one
144
+ fails with `MongoDB model <Type> requires @field metadata`.
145
+
146
+ ## Verify
147
+
148
+ Run the package's specs against the real engine where you can (MongoDB needs a
149
+ replica set for `observe`). `cratis-arc-testing-typescript` covers
150
+ `QueryScenario` for query shape; it does not prove database behavior.
@@ -0,0 +1,2 @@
1
+ Copyright (c) Cratis. All rights reserved.
2
+ Licensed under the MIT license. See LICENSE file in the project root for full license information.
@@ -0,0 +1,125 @@
1
+ ---
2
+ name: cratis-arc-tenancy-typescript
3
+ description: Use when an Arc Node.js server must pick the tenant for each request, prove the caller belongs to it or send data to per-tenant storage. Not for caller authentication, Chronicle namespaces alone or the C# Arc resolver.
4
+ license: MIT
5
+ ---
6
+
7
+ # Tenancy in an Arc Node.js server
8
+
9
+ Arc for TypeScript resolves one tenant per execution, after authentication and
10
+ before your code runs, and carries it as `context.tenantId` through commands,
11
+ queries, services and storage integrations. Three decisions stay separate:
12
+
13
+ | Decision | Made by |
14
+ | --- | --- |
15
+ | Selection: which tenant does the request name? | Arc, from a header, claim, query string, subdomain, fixed value or your resolver |
16
+ | Membership: may this caller use it? | `tenancy.membershipClaim`, your `tenancy.resolve`, or authorization rules |
17
+ | Storage isolation: where do reads and writes go? | The storage integration (MongoDB, Drizzle, Chronicle) |
18
+
19
+ None replaces another. A database per tenant does not stop a caller from naming
20
+ someone else's tenant in a header. The package is `@cratis/arc.core`
21
+ (`ArcApplication`, `TenantResolverType`).
22
+
23
+ ## Choose how the tenant is selected
24
+
25
+ | Configure | Behavior |
26
+ | --- | --- |
27
+ | nothing | Reads the `x-cratis-tenant-id` header unchanged; missing means `tenantId` is `undefined` |
28
+ | `tenancy: { resolve(request, principal) }` | Your resolver alone decides (may be `async`); `undefined` means no tenant; no fallback; Arc does not apply `sources`, `required`, `membershipClaim` or lowercasing to it |
29
+ | `tenancy: { sources: [...] }` | Ordered built-in sources, first nonempty answer wins |
30
+ | `tenancy: { resolverType }` | One .NET-compatible source (defaults to `header` once `tenancy` is present); never combine with `sources` |
31
+
32
+ Built-in sources (`TenantResolverType`):
33
+
34
+ | Source | Option (default) | Reads |
35
+ | --- | --- | --- |
36
+ | `header` | `httpHeader` (`x-cratis-tenant-id`) | request header |
37
+ | `query` | `queryParameter` (`tenantId`) | query string |
38
+ | `claim` | `claimType` (`tenant_id`) | own string claim of an authenticated principal |
39
+ | `fixed` | `fixedTenantId` (`development`) | configured deployment value |
40
+ | `development` | `fixedTenantId` (`development`) | same fixed source; does **not** check the environment |
41
+ | `subdomain` | `baseDomain` (required) | the adapter's verified `native.authority`, never raw `Host`/`X-Forwarded-Host` |
42
+
43
+ Shared options: `required` (unresolved tenant answers 400) and
44
+ `membershipClaim` (a comma-separated own claim of an authenticated principal
45
+ must include the selected tenant, else 403). Tenant IDs are lowercased and must
46
+ be DNS labels (letters, digits, hyphens, at most 63 characters); an invalid
47
+ selected ID answers 400. A single-tenant app uses
48
+ `{ resolverType: TenantResolverType.Fixed, fixedTenantId: 'default' }`.
49
+
50
+ ```typescript
51
+ const builder = ArcApplication.createBuilder({
52
+ authentication: [/* verified handlers */],
53
+ tenancy: {
54
+ sources: [TenantResolverType.Claim, TenantResolverType.Header],
55
+ claimType: 'tenant', membershipClaim: 'tenants', required: true
56
+ }
57
+ });
58
+ ```
59
+
60
+ This tries an own `tenant` claim first, then the header; a missing tenant is
61
+ 400 and a tenant absent from the `tenants` claim is 403. `resolverType`,
62
+ `httpHeader`, `baseDomain`, `queryParameter`, `claimType`, `fixedTenantId`,
63
+ `required` and `membershipClaim` also bind from `Cratis:Arc:Tenancy` in
64
+ `appsettings.json`; `sources` and `resolve` are code-only.
65
+
66
+ ## Prove membership
67
+
68
+ - A header, query string or subdomain value is a request, not proof. When
69
+ tenants separate customers, use the `claim` source with `membershipClaim`, or
70
+ derive the tenant from the principal in `tenancy.resolve` and check
71
+ membership there; return lowercase IDs.
72
+ - Enforce membership in tenancy options or authorization, never in validators:
73
+ a trusted direct caller can lower the blocking severity.
74
+ - Never use `development` or `fixed` to accept a browser-supplied tenant.
75
+ - Treat tenant IDs as internal metadata; keep them out of public URLs and
76
+ error text when a customer name would reveal who else uses the system.
77
+
78
+ ## Storage follows the tenant
79
+
80
+ | Integration | Tenant `acme` | Tenant `default` | No tenant |
81
+ | --- | --- | --- | --- |
82
+ | MongoDB, `database: 'tasks'` | database `tasks+acme` (or `databaseNameResolver`) | `tasks` | request fails |
83
+ | Drizzle | the connection `databaseFactory('acme', context)` returns | `databaseFactory('default', context)` or the `database` option | request fails |
84
+ | Chronicle | namespace `acme` | namespace `default` | namespace `Default` |
85
+
86
+ MongoDB and Drizzle lowercase the tenant; Chronicle passes it unchanged, so
87
+ return lowercase IDs from a custom resolver to keep all three aligned. A command
88
+ returned by a Chronicle reactor runs in the namespace of the triggering event.
89
+ None of these checks membership.
90
+
91
+ ## Read the tenant, and keep it per request
92
+
93
+ Callbacks receive the execution context (`tenantId`, `principal`,
94
+ `correlationId`, `signal`, `allowedSeverity`); deep code can call
95
+ `currentContext()?.tenantId` (`undefined` outside an Arc execution).
96
+
97
+ | Execution | Tenant resolved | Holds |
98
+ | --- | --- | --- |
99
+ | HTTP command or query | once per request, after authentication | request scope |
100
+ | Observable query over SSE | once for the request | whole subscription |
101
+ | WebSocket or multiplexed hub | once when the connection opens | every subscription on it |
102
+ | Reactor-returned command | namespace of the triggering event | that command |
103
+ | Direct call (job) | `tenantId` in the context you pass | that call |
104
+
105
+ Keep tenant-scoped handles (collections, connections, caches) in scoped
106
+ services: a singleton keeps the first tenant that created it. Background work
107
+ that calls the server directly must pass a tenant on purpose. Put the tenant in
108
+ cache keys and logs.
109
+
110
+ ## Specify and verify
111
+
112
+ `CommandScenario.for(...).withContext({ tenantId: 'acme', principal })` proves
113
+ your code uses the tenant it is given; it does not prove the resolver or storage
114
+ configuration. Cover four tenant states (none, `default`, two named tenants),
115
+ a denied selection (403, nothing read or written), concurrent requests for two
116
+ tenants, long-lived work (observable queries, reactors) and direct calls.
117
+ `cratis-arc-testing-typescript` has the scenario setup; use `ArcScenario` with
118
+ HTTP requests to test the resolver itself.
119
+
120
+ ## Route near misses
121
+
122
+ - Authenticating callers, JWT/EasyAuth, identity details: `cratis-arc-command-typescript`
123
+ (`identity-and-introspection.md`).
124
+ - Chronicle namespaces in a .NET or standalone setting: `cratis-chronicle-multi-tenancy`.
125
+ - C# Arc tenant resolution: the C# Arc skills.