@tech4good/platform-tooling 0.1.0-alpha.1 → 0.1.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,7 +5,10 @@ checks local Firestore composite-index definitions against supported lab query
5
5
  calls. It runs as compiled JavaScript on Node.js 22 or later and has no Angular
6
6
  runtime or Firebase credential dependency.
7
7
 
8
- The packaging pilot is currently versioned as `0.1.0-alpha.1`. The query analyzer was
8
+ `t4g-entities` also generates application entity/mock registries from declarations
9
+ beside each model, with watch mode for development. See [entity discovery](#entity-discovery-and-generated-registries).
10
+
11
+ The packaging pilot is currently versioned as `0.1.0-alpha.2`. The query analyzer was
9
12
  extracted from angular-schematics without changing its index-planning behavior.
10
13
  Store-feature discovery also recognizes named and aliased imports from packages
11
14
  whose implementations are outside the scanned app sources.
@@ -17,7 +20,7 @@ This also improves discovery of stores created through an imported Angular
17
20
  Install it as a development dependency:
18
21
 
19
22
  ```bash
20
- npm install --save-dev --save-exact @tech4good/platform-tooling@0.1.0-alpha.1
23
+ npm install --save-dev --save-exact @tech4good/platform-tooling@0.1.0-alpha.2
21
24
  ```
22
25
 
23
26
  Use these package scripts (also emitted by the updated `ng-add` schematic):
@@ -80,7 +83,7 @@ reuses the full query on subsequent loads, without an automatic timestamp cutoff
80
83
  When multiple calls or load stages need the same index, **Also needed for** lists
81
84
  their purposes and locations. The definition is reported and added only once.
82
85
 
83
- These message improvements are included in `0.1.0-alpha.1`; applications pinned to
86
+ These message improvements were introduced in `0.1.0-alpha.1`; applications pinned to
84
87
  `0.1.0-alpha.0` still use the earlier output. Use the local-development commands
85
88
  below to try them before publishing.
86
89
 
@@ -163,7 +166,7 @@ npm run test:indexes
163
166
  npm run pack:tooling
164
167
  ```
165
168
 
166
- The last command creates `tech4good-platform-tooling-0.1.0-alpha.1.tgz` in the repository
169
+ The last command creates `tech4good-platform-tooling-0.1.0-alpha.2.tgz` in the repository
167
170
  root. In a disposable application checkout, install its absolute path as a dev
168
171
  dependency and apply the scripts shown above. A tarball installation exercises
169
172
  the same compiled files, exports, and executable that npm consumers receive.
@@ -200,7 +203,7 @@ cd /path/to/angular-schematics
200
203
  npm run pack:tooling
201
204
 
202
205
  cd /path/to/math-pets
203
- npm install --no-save --package-lock=false /path/to/angular-schematics/tech4good-platform-tooling-0.1.0-alpha.1.tgz
206
+ npm install --no-save --package-lock=false /path/to/angular-schematics/tech4good-platform-tooling-0.1.0-alpha.2.tgz
204
207
  ./node_modules/.bin/t4g-check-firestore-indexes
205
208
  ```
206
209
 
@@ -246,15 +249,15 @@ the Angular/schematics version.
246
249
 
247
250
  ### 1. Prepare the version
248
251
 
249
- This checkout is prepared for `0.1.0-alpha.1`. It is already set in the package
252
+ This checkout is prepared for `0.1.0-alpha.2`. It is already set in the package
250
253
  manifest, root lockfile, and generated dependency; do not bump again to publish
251
254
  this release.
252
255
 
253
256
  For a subsequent release, choose an unused version and bump only this workspace.
254
- For example, after publishing `0.1.0-alpha.1`, prepare the next alpha with:
257
+ For example, after publishing `0.1.0-alpha.2`, prepare the next alpha with:
255
258
 
256
259
  ```bash
257
- npm version 0.1.0-alpha.2 --workspace @tech4good/platform-tooling --no-git-tag-version --ignore-scripts
260
+ npm version 0.1.0-alpha.3 --workspace @tech4good/platform-tooling --no-git-tag-version --ignore-scripts
258
261
  ```
259
262
 
260
263
  Replace the example version with the one being released. This updates
@@ -266,6 +269,9 @@ Then update these files together:
266
269
 
267
270
  - Set `devDependencies["@tech4good/platform-tooling"]` in
268
271
  `src/ng-add/files/package.json.template` to the same exact version.
272
+ - Update the root `package.json` dependency on platform-tooling as well; schematics
273
+ use its registry generator. Run `npm install --package-lock-only --ignore-scripts`
274
+ to synchronize the lockfile after changing dependency pins.
269
275
  - Record the release's changes under that version in `packages/tooling/CHANGELOG.md`.
270
276
  - Update versioned installation examples and remove any obsolete "unpublished"
271
277
  wording in this README and the root README as part of preparing the release.
@@ -325,17 +331,17 @@ different contents, so later changes require a new version.
325
331
  For this alpha (substitute the actual version for later releases):
326
332
 
327
333
  ```bash
328
- npm view @tech4good/platform-tooling@0.1.0-alpha.1 version
334
+ npm view @tech4good/platform-tooling@0.1.0-alpha.2 version
329
335
  npm view @tech4good/platform-tooling dist-tags
330
- git tag -a platform-tooling-v0.1.0-alpha.1 -m "Release @tech4good/platform-tooling 0.1.0-alpha.1"
336
+ git tag -a platform-tooling-v0.1.0-alpha.2 -m "Release @tech4good/platform-tooling 0.1.0-alpha.2"
331
337
  ```
332
338
 
333
- Confirm the first command returns `0.1.0-alpha.1` and the `alpha` tag points to
339
+ Confirm the first command returns `0.1.0-alpha.2` and the `alpha` tag points to
334
340
  that version. Create the Git tag on the release commit, and push that commit
335
341
  through the repository's normal Git workflow. Then push this specific tag:
336
342
 
337
343
  ```bash
338
- git push origin platform-tooling-v0.1.0-alpha.1
344
+ git push origin platform-tooling-v0.1.0-alpha.2
339
345
  ```
340
346
 
341
347
  The `platform-tooling-v` prefix distinguishes tooling releases from the existing
@@ -347,7 +353,7 @@ npm before releasing angular-schematics with a template that references it.
347
353
  From the application's directory, install the chosen published version:
348
354
 
349
355
  ```bash
350
- npm install --save-dev --save-exact @tech4good/platform-tooling@0.1.0-alpha.1
356
+ npm install --save-dev --save-exact @tech4good/platform-tooling@0.1.0-alpha.2
351
357
  npm run check:indexes
352
358
  ```
353
359
 
@@ -355,3 +361,91 @@ For first-time adoption, also add or replace `check:indexes` and `fix:indexes`
355
361
  with the commands in [Use in an application](#use-in-an-application) before running the check.
356
362
  Commit the application's updated `package.json` and lockfile. A tooling upgrade
357
363
  does not require upgrading angular-schematics in that application.
364
+
365
+
366
+ ## Entity discovery and generated registries
367
+
368
+ Starting in `0.1.0-alpha.2`, `t4g-entities` collects entity definitions from the
369
+ consuming application. Runtime helpers come from `@tech4good/platform-data`.
370
+ No application models or fixtures are published inside platform-tooling.
371
+
372
+ Declare an exported constant beside its interface in `*.model.ts`:
373
+
374
+ ```ts
375
+ import { DataEntity, defineEntity } from '@tech4good/platform-data';
376
+ export interface Problem extends DataEntity { title: string; }
377
+ export const problemEntity = defineEntity<Problem>({ collection: 'problems' });
378
+ ```
379
+
380
+ The store uses `problemEntity.collection`. Optionally export a mock definition
381
+ from `*.mock.ts`, importing the entity directly from its relative model file:
382
+
383
+ ```ts
384
+ import { defineEntityMock } from '@tech4good/platform-data/testing';
385
+ import { problemEntity } from './problem.model';
386
+
387
+ // Reuse the mock store and fixtures declared in this file.
388
+ export const problemMock = defineEntityMock(problemEntity, {
389
+ store: ProblemMockDB,
390
+ seeds: PROBLEM_DB,
391
+ });
392
+ ```
393
+
394
+ Without a custom mock definition, generation supplies an empty in-memory mock
395
+ collection. With one, the concrete mock-store type and fixture types are retained.
396
+ Factories and seed arrays are evaluated by the application, never by discovery.
397
+ Named import aliases and namespace imports are supported. Collection names must
398
+ be literals. Definition calls must initialize exported top-level constants;
399
+ dynamic collection expressions and indirect/barrel model imports in mock
400
+ definitions are rejected with an actionable filename. Ordinary model interfaces
401
+ without `defineEntity` are ignored; they may be unrelated UI types.
402
+
403
+ ```bash
404
+ # Generate once, or verify committed generated files without writing.
405
+ npx t4g-entities
406
+ npx t4g-entities --check
407
+
408
+ # Generate before starting the child process, then watch additions/edits/deletions.
409
+ npx t4g-entities --watch -- ng serve
410
+ npx t4g-entities --watch -- jest --watch
411
+
412
+ # Generate and run a one-off command; propagate its exit status.
413
+ npx t4g-entities -- ng build
414
+
415
+ # Inspect/help, or use another project's root.
416
+ npx t4g-entities --help
417
+ npx t4g-entities --project-root /path/to/math-pets
418
+ ```
419
+
420
+ The default scan root is `src/app`. The two generated files under
421
+ `src/app/core/store` are `entities.generated.ts` (`APP_ENTITIES`, `AppEntityMap`)
422
+ and `entity-mocks.generated.ts` (`APP_ENTITY_MOCKS`). `--source-root` and
423
+ `--output-dir` accept project-relative directories for other layouts. Output is
424
+ sorted and unchanged files are not rewritten. Generation refuses to overwrite
425
+ handwritten output files; duplicates, invalid declarations, and dangling mocks
426
+ fail before changing the registries. It does not edit services, security rules,
427
+ indexes, or model files.
428
+
429
+ The watcher polls definition files every 300 ms, including newly created
430
+ folders. Invalid edits report an error and retain the last valid registry;
431
+ correcting the file resumes generation. The supervised command stops the watcher
432
+ when it exits. Interrupting the CLI also terminates its command process group
433
+ on POSIX systems. Watch mode is for development; use one-shot generation or
434
+ `--check` as the build/CI gate.
435
+
436
+ Generated applications wire this into `npm start`, `npm run watch`, and
437
+ `npm run test:watch`; build/test/lint regenerate first. Direct `ng`/`jest` commands
438
+ bypass those scripts. Keep generated files in git for editor support and review,
439
+ and run `check:entities` before regeneration when CI should detect stale output.
440
+ No shared-package release is needed when an app adds an entity.
441
+
442
+ Import `APP_ENTITY_MOCKS` only from mock/test composition. Generated apps replace
443
+ `data.providers.ts` with `data.providers.prod.ts` in production, so fixture modules
444
+ are excluded from the production import graph. The real registry has no mock
445
+ imports. The index checker understands collection names read through
446
+ `problemEntity.collection`.
447
+
448
+ For schematic authors, the package also exports the pure
449
+ `generateEntityRegistrySources(sources, options)` API for virtual file trees and
450
+ `generateEntityRegistries(options)` / `watchEntityRegistries(options, callbacks)`
451
+ for disk-based workflows. Sources are a map of project-relative paths to text.
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,141 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ const node_child_process_1 = require("node:child_process");
5
+ const entity_registry_1 = require("./entity-registry");
6
+ const help = `Usage: t4g-entities [--check | --watch] [--project-root <path>] [-- <command> ...]
7
+
8
+ Discover defineEntity exports in *.model.ts and defineEntityMock exports in *.mock.ts.
9
+ Generate entities.generated.ts and entity-mocks.generated.ts inside the app.
10
+
11
+ --check Fail if generated files are missing/stale; do not write
12
+ --watch Regenerate when definitions are added, changed, or removed
13
+ --project-root <path> Default: current directory
14
+ --source-root <path> Project-relative scan directory (default: src/app)
15
+ --output-dir <path> Project-relative output directory (default: src/app/core/store)
16
+ -- <command> ... Generate first, then run a command; keep watcher alive until it exits
17
+ --help, -h Show this help
18
+
19
+ Examples: t4g-entities --watch -- ng serve
20
+ t4g-entities -- ng build
21
+ t4g-entities --check
22
+
23
+ No app code is executed during discovery. No Firebase connection or deployment is made.`;
24
+ /**
25
+ * Parse generator flags before `--`; pass subsequent arguments unchanged to the
26
+ * child command. Generation must succeed before starting Angular or another tool.
27
+ * In watch mode this process owns both the poller and the child's lifetime.
28
+ */
29
+ async function main(args) {
30
+ const options = {};
31
+ let check = false;
32
+ let watch = false;
33
+ let command = [];
34
+ for (let i = 0; i < args.length; i++) {
35
+ const arg = args[i];
36
+ if (arg === '--') {
37
+ command = args.slice(i + 1);
38
+ if (!command.length)
39
+ throw new Error('-- requires a command.');
40
+ break;
41
+ }
42
+ if (arg === '--help' || arg === '-h') {
43
+ console.log(help);
44
+ return 0;
45
+ }
46
+ if (arg === '--check')
47
+ check = true;
48
+ else if (arg === '--watch')
49
+ watch = true;
50
+ else if (['--project-root', '--source-root', '--output-dir'].includes(arg)) {
51
+ const value = args[++i];
52
+ if (!value || value.startsWith('-'))
53
+ throw new Error(`${arg} requires a path.`);
54
+ if (arg === '--project-root')
55
+ options.projectRoot = value;
56
+ if (arg === '--source-root')
57
+ options.sourceRoot = value;
58
+ if (arg === '--output-dir')
59
+ options.outputDir = value;
60
+ }
61
+ else
62
+ throw new Error(`Unknown argument: ${arg}`);
63
+ }
64
+ if (check && (watch || command.length))
65
+ throw new Error('--check cannot be combined with --watch or a command.');
66
+ const report = (result) => {
67
+ if (result.changed.length)
68
+ console.log(`[entities] ${result.collections.length} collections; ${result.success ? 'generated' : 'stale'}: ${result.changed.join(', ')}`);
69
+ };
70
+ const watcher = watch ? (0, entity_registry_1.watchEntityRegistries)(options, {
71
+ onChange: report,
72
+ onError: error => console.error(`[entities] ${error.message} Fix the definition to regenerate; previous output is unchanged.`),
73
+ }) : undefined;
74
+ if (!watch) {
75
+ const result = (0, entity_registry_1.generateEntityRegistries)({ ...options, check });
76
+ report(result);
77
+ if (!result.success)
78
+ return 1;
79
+ }
80
+ if (!command.length && !watcher)
81
+ return 0;
82
+ return new Promise(resolve => {
83
+ // Spawn without a shell to preserve argument boundaries. A separate POSIX
84
+ // process group lets shutdown reach descendants such as npm -> ng serve.
85
+ const child = command.length ? (0, node_child_process_1.spawn)(command[0], command.slice(1), {
86
+ cwd: options.projectRoot, stdio: 'inherit', detached: process.platform !== 'win32',
87
+ }) : undefined;
88
+ let finished = false;
89
+ let stopping = false;
90
+ let killTimer;
91
+ /** Shared exit path for spawn errors, child exits and wrapper termination. */
92
+ function finish(code) {
93
+ if (finished)
94
+ return;
95
+ finished = true;
96
+ watcher?.close();
97
+ if (killTimer)
98
+ clearTimeout(killTimer);
99
+ process.off('SIGINT', interrupt);
100
+ process.off('SIGTERM', terminate);
101
+ resolve(code);
102
+ }
103
+ function kill(signal) {
104
+ if (!child?.pid)
105
+ return;
106
+ try {
107
+ if (process.platform !== 'win32')
108
+ process.kill(-child.pid, signal);
109
+ else
110
+ child.kill(signal);
111
+ }
112
+ catch (error) {
113
+ if (error.code !== 'ESRCH')
114
+ throw error;
115
+ }
116
+ }
117
+ /** Stop polling first, allow graceful child cleanup, then bound shutdown time. */
118
+ function stop(signal) {
119
+ if (stopping)
120
+ return;
121
+ stopping = true;
122
+ watcher?.close();
123
+ if (!child) {
124
+ finish(signal === 'SIGINT' ? 130 : 143);
125
+ return;
126
+ }
127
+ kill(signal);
128
+ killTimer = setTimeout(() => { kill('SIGKILL'); finish(signal === 'SIGINT' ? 130 : 143); }, 2000);
129
+ }
130
+ const interrupt = () => stop('SIGINT');
131
+ const terminate = () => stop('SIGTERM');
132
+ process.on('SIGINT', interrupt);
133
+ process.on('SIGTERM', terminate);
134
+ child?.once('error', error => { console.error(error.message); finish(1); });
135
+ child?.once('exit', (code, signal) => { kill('SIGTERM'); finish(code ?? (signal === 'SIGINT' ? 130 : 143)); });
136
+ });
137
+ }
138
+ main(process.argv.slice(2)).then(code => { process.exitCode = code; }).catch(error => {
139
+ console.error(`[entities] ${error instanceof Error ? error.message : String(error)}`);
140
+ process.exitCode = 1;
141
+ });
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Source-only entity discovery shared by the CLI and Angular schematics.
3
+ * Parse declarations instead of importing application modules: importing them
4
+ * could initialize Angular/Firebase or pull mock fixtures into build tooling.
5
+ * Generated files belong to the consuming app, not the published data package.
6
+ */
7
+ /** Filesystem settings; sourceRoot/outputDir must remain project-relative. */
8
+ export interface EntityRegistryOptions {
9
+ /** Filesystem project root for disk operations; defaults to the current directory. */
10
+ projectRoot?: string;
11
+ /** Project-relative directory containing entity files. Defaults to src/app. */
12
+ sourceRoot?: string;
13
+ /** Project-relative generated-file directory. Defaults to src/app/core/store. */
14
+ outputDir?: string;
15
+ }
16
+ export interface EntityRegistryResult {
17
+ /** Generated TypeScript text keyed by project-relative destination path. */
18
+ files: Record<string, string>;
19
+ /** Discovered collection names in deterministic order. */
20
+ collections: string[];
21
+ }
22
+ /**
23
+ * Produce both registry modules from project-relative source text, with no disk
24
+ * access or app execution. Also accepts the leading slash used by schematic Trees.
25
+ * Models are discovered first, then mocks are matched by direct relative import.
26
+ * Invalid declarations, duplicate collections and orphan mocks throw before any
27
+ * output is returned. Files without entity helper calls need no registration.
28
+ */
29
+ export declare function generateEntityRegistrySources(sources: Record<string, string>, options?: Pick<EntityRegistryOptions, 'sourceRoot' | 'outputDir'>): EntityRegistryResult;
30
+ /**
31
+ * Discover from disk and write changed registries, or compare only with check:true.
32
+ * `changed` lists different/missing outputs in either mode; `success` is false
33
+ * only when check mode finds stale output. Discovery or filesystem errors throw.
34
+ */
35
+ export declare function generateEntityRegistries(options?: EntityRegistryOptions & {
36
+ check?: boolean;
37
+ }): {
38
+ changed: string[];
39
+ success: boolean;
40
+ /** Generated TypeScript text keyed by project-relative destination path. */
41
+ files: Record<string, string>;
42
+ /** Discovered collection names in deterministic order. */
43
+ collections: string[];
44
+ };
45
+ /**
46
+ * Generate synchronously before starting a polling watcher, so callers can start
47
+ * Angular only after valid modules exist. Polling finds new/deleted directories
48
+ * across Node platforms. Later invalid edits report onError and retain the last
49
+ * valid output; another source edit retries. The caller must close the watcher.
50
+ */
51
+ export declare function watchEntityRegistries(options: EntityRegistryOptions, callbacks?: {
52
+ onChange?: (result: ReturnType<typeof generateEntityRegistries>) => void;
53
+ onError?: (error: Error) => void;
54
+ intervalMs?: number;
55
+ }): {
56
+ close(): void;
57
+ };