Skip to content

Commit 959c26b

Browse files
feat(cli,create-objectstack): the starter wires src/security and src/datasets, os g permission/dataset, AGENTS.md names the package manager (#30258)
<!-- claude-projects-attribution: {"github_login":"os-bill"} --> _Requested by **Bill** · [project thread](https://claude.ai/code/project/chan_016iMXWSZDzqWRWvWzdNo8wg?thread=cmsg_016iMXWSZDzqWRWvWzdNo8wgMbwUoA3jpCJqhx1Epktwiw)_ domain:server#4 · os-bill · session_01Utp6CZMkHvuDeVYgTD73qF ## 维护者速读 - 改了什么:新建项目(`npm create objectstack`)自带已接线的空目录 `src/security`(权限集)和 `src/datasets`(分析数据集);`os g permission` / `os g dataset` 两个新类型往这两处写文件;生成的 AGENTS.md 按建项目时实际用的包管理器写 `pnpm run …` 或 `npm run …`。 - 为什么改:真实用户走查时,有人登录的应用必须有权限集、仪表盘要绑数据集,但新项目里没地方放、`os g` 也生成不了,只能手工接线;pnpm 项目的 AGENTS.md 还一直写 `npm run`。 - 风险与回滚:只动脚手架模板、CLI 生成器和文档,不碰 spec 与运行时;两个新目录是空 barrel,老项目不受影响。回滚即 revert 本 PR。 - 先看:`packages/cli/src/commands/generate.ts`(permission / dataset 两个生成器,权限集默认授予读/建/改、`readScope: 'own'`)、`packages/create-objectstack/src/templates/blank/objectstack.config.ts`(新增两条接线)、`packages/create-objectstack/src/index.ts`(AGENTS.md 填入包管理器)。 - 两分钟验证:`pnpm --filter @objectstack/cli exec vitest run --project unit test/generate-scaffold-validates.test.ts src/commands/generate-permission-dataset.pin.test.ts`,预期全部通过,其中 `os g 'permission'`、`os g 'dataset'` 两条在 validate/build/lint 下零发现。 - 需要你做的:无,席位落地。 Fixes #30123 Clause-②: yes (widening) — `os generate` accepts two new type values, `permission` and `dataset`; no flag or export is removed or narrowed. Metadata-protocol: none ## What changes **Blank starter (`create-objectstack`).** `src/security/index.ts` and `src/datasets/index.ts` ship as empty barrels, and `objectstack.config.ts` hands them to the stack's existing `permissions` and `datasets` keys through the same `exportsOf()` helper as the eight directories it already wired. Both keys exist on `ObjectStackDefinitionSchema` today (`permissions: z.array(PermissionSetSchema)`, `datasets: z.array(DatasetSchema)`), so no spec change. The generated AGENTS.md "Project Structure" block names both directories, and the two READMEs list them. **`os generate permission NAME [--object OBJECT]`** writes `src/security/NAME.permission.ts`. The type key is the registry's own (`permission`, file pattern `*.permission.ts`), and the stack key is `singularToPlural('permission')` = `permissions`, so the generator rides the existing roster machinery: `os init` wires it, `os g` reports reach, and every derived pin measures it. The scaffold is a `definePermissionSet` granting the bound object (from `--object`, or the stack's only object) read, create and edit without delete, with `readScope: 'own'` written. Without a depth, a read grant on a private object is reported by `security-private-no-readscope` (info), which the zero-findings pin refused; `'own'` states the same reach the object's sharing model gives instead of widening it, and the emitted comment names `'org'`. `isDefault` is not written, and the comment says what it would do. **`os generate dataset NAME [--object OBJECT]`** writes `src/datasets/NAME.dataset.ts`: a `defineDataset` over the bound object with a `record_count` count measure, grouped by the record's title field when the object has one (no dimension otherwise). `defineDataset` types the literal as a `Dataset`, so it needs no `as const` (the card's last measured point). **Generated AGENTS.md names the package manager.** The template's eight `npm run` occurrences are `{{PM}} run`, and `writeAgentGuides` fills `{{PM}}` with the manager `detectPackageManager()` chose for the same run, the one the install line and "Next steps" already name. Both written copies (`AGENTS.md`, `.github/copilot-instructions.md`) carry it. **Docs.** `content/docs/deployment/cli.mdx` (examples, types table, `--object`, "What it does") and `packages/cli/README.md` list the two types. Deviation from the dispatch's suggested route: the types are `permission` and `dataset`, not `permission-set`. The generator key is the registry type key, which names both the file infix (`metadataFileName`) and the stack key (`singularToPlural`); `permission-set` has no registry entry and would map to no stack key. ## Tests - `packages/cli/src/commands/generate-permission-dataset.pin.test.ts` (new, unit): roster facts (directory, stack key, binds, file name), each scaffold loaded through `bundle-require` as `os validate` loads it parses under `PermissionSetSchema` / `DatasetSchema` with the name `os g` reports, grants or covers only the bound object, and the no-title-field dataset case. - Derived pins that now cover both types without edits: `generate-scaffold-validates` (zero findings at any severity across validate/build/lint), `scaffold-emission-typechecks`, `create-objectstack-wiring-parity` (blank config and barrels byte-equal to what `os init` renders), `generate-file-name-registry-parity`, `generate-scaffold-wiring`, and the nightly `generate-scaffolds-reach-stack.e2e` / `generate-scaffold-gates.e2e` (run locally under `OS_TEST_TIERS=nightly`). - `packages/create-objectstack/src/scaffold-next-steps-pm.test.ts`: a new describe scaffolds through the real CLI under a stub-pnpm PATH and a pnpm-less PATH and reads both written guides back: `pnpm run` and no bare `npm run`; control `npm run` and no `pnpm`; no unfilled placeholder either way. ## Acceptance notes - The empty barrel comment reads "The permissions in this directory … a permission exported here": it is rendered by `os init`'s `renderEmptyWiredBarrel` from the type key and must stay byte-equal to it (wiring-parity pin), so the starter's copy says "permission", not "permission set". - `src/security` holds permission sets only, because its barrel feeds the `permissions` key. Positions, sharing rules and other security metadata still need their own barrel and key. ## Verification <details><summary>Local runs, on ce2e6f6 (before the one merge of origin/main) unless a line names c45f7cb</summary> - `pnpm --filter create-objectstack exec vitest run`: Test Files 23 passed (23), Tests 362 passed (362), on ce2e6f6 and again on c45f7cb. - Ablation: `.replace(/\{\{PM\}\}/g, pm)` removed from `index.ts` through `scripts/ablation-replace.mjs` ⇒ both new AGENTS.md cases red (2 failed); restored, blob equal to HEAD, `git diff HEAD` empty. - `pnpm --filter @objectstack/cli exec vitest run --project unit` : 384 files, 5394 passed, 29 skipped; the 2 published-subpath files first refused because `packages/cli` was not built, and passed (29/29) after `pnpm --filter @objectstack/cli build`. - c45f7cb, after the merge: rebuilt spec and cli, then 7 targeted unit files (the new pin, scaffold-validates, wiring-parity, file-name parity, scaffold-wiring, emission-typechecks, docs enumeration parity): 169 passed. - `--project integration` `test/create-objectstack-stack-reach.test.ts` (and the picklist pin): 9 passed. `OS_TEST_TIERS=nightly` `generate-scaffolds-reach-stack.e2e` + `generate-scaffold-gates.e2e`: 58 passed. - `pnpm --filter @objectstack/cli --filter create-objectstack run typecheck`: exit 0. `pnpm lint`: exit 0. - `dispatch-gates --commands` (93 families), `--ran`: 89 run green, 4 NOT MEASURED (recorded exit 3, prerequisite not met in this shallow worktree: `check-plugin-teardown-shape --self-test` needs an unshallow fetch, `check:skill-examples` needs client builds, `check:dual-build-cjs-loads` and `check:i18n-coverage` need packages outside this build closure). CI runs all four. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01Utp6CaSDwi65gmZEL5wiWy --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6CaSDwi65gmZEL5wiWy)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent f9e5bef commit 959c26b

13 files changed

Lines changed: 397 additions & 19 deletions

File tree

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@objectstack/cli': patch
3+
'create-objectstack': patch
4+
---
5+
6+
feat(cli,create-objectstack): a new project has a wired place for permission sets and datasets, `os g permission` / `os g dataset` write them, and the generated AGENTS.md names the package manager the project was created with
7+
8+
Clause-②: yes (widening)
9+
Metadata-protocol: none
10+
11+
- **`create-objectstack`: the blank starter ships `src/security/index.ts` and `src/datasets/index.ts`**, empty barrels already handed to the stack's `permissions` and `datasets` keys in `objectstack.config.ts`, like the eight directories it wired before. A permission set or a dataset exported from them is loaded and counted by `validate` with no edit to the config. The generated `AGENTS.md` lists both directories.
12+
- **`@objectstack/cli`: `os g permission NAME [--object OBJECT]`** writes `src/security/NAME.permission.ts`, a `definePermissionSet` granting read, create and edit (no delete) on the object `--object` names, or the stack's only object, with `readScope: 'own'` declared. **`os g dataset NAME [--object OBJECT]`** writes `src/datasets/NAME.dataset.ts`, a `defineDataset` over that object with a `record_count` measure, grouped by the record's title field when it has one. `defineDataset` types the literal, so it needs no `as const`. Both pass `os validate`, `os build` and `os lint` with no finding on a fresh project. `os init` wires both directories too.
13+
- **`create-objectstack`: the generated `AGENTS.md` (and `.github/copilot-instructions.md`) says `pnpm run validate` in a project created with pnpm**, and `npm run …` in one created with npm, the same package manager the install line and "Next steps" name. It used to say `npm run` in every project.

‎content/docs/deployment/cli.mdx‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2342,6 +2342,8 @@ os g dashboard sales # Generate a dashboard
23422342
os g app sales --object customer # Generate an app whose navigation opens Customer
23432343
os g skill lead_qual # Generate an AI skill
23442344
os g picklist industry # Generate a shared option list select fields name
2345+
os g permission sales_user --object customer # Generate a permission set that grants Customer
2346+
os g dataset customer_metrics --object customer # Generate a dataset dashboard widgets bind to
23452347
23462348
os g action escalate --object customer --flow customer_changed_flow # Name the flow when there are several
23472349
os g object task -d lib/ # Override target directory
@@ -2360,6 +2362,8 @@ os g object task --dry-run # Preview without writing
23602362
| `app` | `src/apps/` | `NAME.app.ts` | `apps` | Application navigation |
23612363
| `skill` | `src/skills/` | `NAME.skill.ts` | `skills` | AI skill — the ADR-0063 extension primitive |
23622364
| `picklist` | `src/picklists/` | `NAME.picklist.ts` | `picklists` | Shared option list that select fields reference by name |
2365+
| `permission` | `src/security/` | `NAME.permission.ts` | `permissions` | Permission set: what a signed-in user may do with an object |
2366+
| `dataset` | `src/datasets/` | `NAME.dataset.ts` | `datasets` | Analytics dataset: the dimensions and measures dashboard widgets bind to |
23632367
23642368
<Callout type="info" title="Why generated files carry a type infix">
23652369
Every scaffold is written as `NAME.TYPE.ts`, and the infix is read from the
@@ -2413,12 +2417,12 @@ the rules a JSON Schema can express and names the rest under
24132417
**Options:**
24142418
- `-d, --dir <directory>` — Override target directory
24152419
- `--dry-run` — Preview without writing files
2416-
- `--object <object>` — The object a `flow`, `action` or `app` binds; default: the stack's only object
2420+
- `--object <object>` — The object a `flow`, `action`, `app`, `permission` or `dataset` binds; default: the stack's only object
24172421
- `--flow <flow>` — The flow an `action` runs; default: the stack's only flow
24182422
24192423
**What it does:**
2420-
1. For a type that names an object (`object`, `view`, `action`, `flow`, `app`), reads `manifest.namespace` from the project config (`objectstack.config.ts`, `.js` or `.mjs`) and prefixes the object name with it, and resolves every object or flow the scaffold binds against the stack that config loads (see above)
2421-
2. Creates the TypeScript file — an `object` declared with `ObjectSchema.create({ … })`, the same shape the `os init` templates write; a `skill` declared with `defineSkill({ … })`; a `picklist` declared with `definePicklist({ … })`, which a select field names with `Field.select({ picklist: 'NAME' })` in place of its own `options`, and which the server resolves into that field's `options`; the other types as typed literals (`UI.View`, `UI.Action`, `Automation.Flow`, `UI.Dashboard`, `UI.App`)
2424+
1. For a type that names an object (`object`, `view`, `action`, `flow`, `app`, `permission`, `dataset`), reads `manifest.namespace` from the project config (`objectstack.config.ts`, `.js` or `.mjs`) and prefixes the object name with it, and resolves every object or flow the scaffold binds against the stack that config loads (see above)
2425+
2. Creates the TypeScript file — an `object` declared with `ObjectSchema.create({ … })`, the same shape the `os init` templates write; a `skill` declared with `defineSkill({ … })`; a `picklist` declared with `definePicklist({ … })`, which a select field names with `Field.select({ picklist: 'NAME' })` in place of its own `options`, and which the server resolves into that field's `options`; a `permission` set declared with `definePermissionSet({ … })`, granting the bound object; a `dataset` declared with `defineDataset({ … })` over the bound object, with a record-count measure; the other types as typed literals (`UI.View`, `UI.Action`, `Automation.Flow`, `UI.Dashboard`, `UI.App`)
24222426
3. Creates or updates the barrel `index.ts` in the target directory
24232427
4. Shows a hint to run `objectstack validate`
24242428

‎packages/cli/README.md‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,12 +60,17 @@ os compile
6060
| `os generate <type> <name>` | Generate metadata files (alias: `os g`) |
6161
| `os create <type> [name]` | Scaffold a standalone **kernel code** plugin project (the `Plugin` contract, built by `tsc`) from a built-in template |
6262

63-
Available generate types: `object`, `view`, `action`, `flow`, `dashboard`, `app`, `skill`, `picklist`
63+
Available generate types: `object`, `view`, `action`, `flow`, `dashboard`, `app`, `skill`, `picklist`, `permission`, `dataset`
6464

6565
`picklist` writes a shared option list (`src/picklists/<name>.picklist.ts`, with
6666
`definePicklist`). A select field names it with `Field.select({ picklist: '<name>' })`
6767
in place of its own `options`, and the server serves that field with the list's options.
6868

69+
`permission` writes a permission set (`src/security/<name>.permission.ts`, with
70+
`definePermissionSet`) granting the object `--object` names, or the stack's only object.
71+
`dataset` writes an analytics dataset (`src/datasets/<name>.dataset.ts`, with
72+
`defineDataset`) over that object, which dashboard and report widgets bind to by name.
73+
6974
`agent` is **retired** (ADR-0063 §2): agents are platform-internal, so a scaffolded
7075
`src/agents/*.ts` validated, published and was then filtered out of the runtime
7176
catalog without a word. `os g agent` now says so and points at skills — the
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* PIN: `os generate permission NAME` and `os generate dataset NAME` write a
5+
* permission set and an analytics dataset into the directories the blank
6+
* starter wires, each bound to an object the stack declares.
7+
*
8+
* ## What was measured before the rows existed
9+
*
10+
* On `origin/main` 5fa9375e, `os generate permission` and
11+
* `os generate dataset` each printed `Unknown type:` and exited 1, and the
12+
* blank starter wired no `src/security` or `src/datasets` barrel. An app that
13+
* real users sign in to needs a permission set, and a dashboard widget binds
14+
* to a dataset; both could be written only by hand, in a directory the author
15+
* also had to wire by hand.
16+
*
17+
* ## What this file holds, and what it leaves to the derived pins
18+
*
19+
* The roster facts the starter depends on — the type key, the directory, the
20+
* stack key — and the scaffold's own shape: it parses under the schema the
21+
* stack key carries, under the name `os g` reports it reached, and it names
22+
* the object it was bound to, never one derived from its own name. That every
23+
* scaffold passes `os validate`, `os build` and `os lint` with zero findings,
24+
* type-checks, and reaches the stack is held for the whole roster by
25+
* `test/generate-scaffold-validates.test.ts`,
26+
* `test/scaffold-emission-typechecks.test.ts` and
27+
* `test/generate-scaffolds-reach-stack.e2e.test.ts`; the blank starter's
28+
* wiring by `test/create-objectstack-wiring-parity.test.ts`.
29+
*
30+
* Every other fact is READ off the roster (`GENERATOR_SCAFFOLD_TARGETS`) and
31+
* the registry (`metadataFileName`).
32+
*/
33+
34+
import { afterAll, describe, expect, it } from 'vitest';
35+
import fs from 'node:fs';
36+
import path from 'node:path';
37+
import { fileURLToPath } from 'node:url';
38+
import { bundleRequire } from 'bundle-require';
39+
import { PermissionSetSchema } from '@objectstack/spec/security';
40+
import { DatasetSchema } from '@objectstack/spec/ui';
41+
import { GENERATOR_SCAFFOLD_TARGETS, type ScaffoldObjectBinding } from './generate.js';
42+
import { metadataFileName } from '../utils/metadata-file-name.js';
43+
import { BUNDLE_REQUIRE_EXTERNALS } from '../utils/config.js';
44+
45+
const STEM = 'sales_user';
46+
47+
/** Deliberately NOT named like the item: a binding derived from the name would miss it. */
48+
const TARGET: ScaffoldObjectBinding = {
49+
name: 'pin_account',
50+
label: 'Account',
51+
fields: ['name', 'industry'],
52+
displayField: 'name',
53+
};
54+
55+
const target = (type: string) => GENERATOR_SCAFFOLD_TARGETS.find((t) => t.type === type);
56+
57+
/**
58+
* Inside this package's own `node_modules`, for the reason
59+
* `test/generate-scaffold-validates.test.ts` gives: git-ignored, and the
60+
* scaffold's `@objectstack/spec/*` import resolves from here exactly as it
61+
* would in an author's project.
62+
*/
63+
const TMP_ROOT = fs.mkdtempSync(
64+
path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'node_modules', '.generate-permission-dataset-pin-'),
65+
);
66+
67+
afterAll(() => {
68+
fs.rmSync(TMP_ROOT, { recursive: true, force: true });
69+
});
70+
71+
/** Materialize a scaffold through the loader `os validate` uses. */
72+
async function loadScaffold(type: string, object: ScaffoldObjectBinding): Promise<Record<string, unknown>> {
73+
const gen = target(type);
74+
if (!gen) throw new Error(`no \`${type}\` generator on the roster`);
75+
const dir = fs.mkdtempSync(path.join(TMP_ROOT, `${type}-`));
76+
const file = path.join(dir, metadataFileName(type, STEM) ?? 'unnamed.ts');
77+
fs.writeFileSync(file, gen.generate(STEM, undefined, { object }), 'utf8');
78+
const { mod } = await bundleRequire({ filepath: file, external: BUNDLE_REQUIRE_EXTERNALS });
79+
return ((mod as { default?: unknown }).default ?? mod) as Record<string, unknown>;
80+
}
81+
82+
describe('`os generate permission` and `os generate dataset` are on the roster, where the starter wires them', () => {
83+
it.each([
84+
['permission', 'src/security', 'permissions'],
85+
['dataset', 'src/datasets', 'datasets'],
86+
])('%s scaffolds into %s, collected under the `%s` stack key', (type, dir, stackKey) => {
87+
const gen = target(type);
88+
expect(gen, `the \`${type}\` generator`).toBeDefined();
89+
expect(gen!.defaultDir).toBe(dir);
90+
expect(gen!.stackKey).toBe(stackKey);
91+
// Both bind an object the stack declares, from `--object` or the only one.
92+
expect(gen!.binds).toEqual({ object: 'flag' });
93+
expect(gen!.namesObject).toBe(true);
94+
expect(gen!.requires).toEqual([]);
95+
});
96+
97+
it.each(['permission', 'dataset'])('writes NAME.%s.ts, the registry\'s own pattern for the kind', (type) => {
98+
expect(metadataFileName(type, STEM)).toBe(`${STEM}.${type}.ts`);
99+
});
100+
});
101+
102+
describe('the permission scaffold is a set that grants the bound object', () => {
103+
it('parses as a permission set named what `os g` reports it reached', async () => {
104+
const set = await loadScaffold('permission', TARGET);
105+
expect(PermissionSetSchema.safeParse(set).success).toBe(true);
106+
expect(set.name).toBe(target('permission')!.itemName(STEM));
107+
});
108+
109+
it('grants the bound object, and only it, without delete', async () => {
110+
const set = await loadScaffold('permission', TARGET);
111+
expect(Object.keys(set.objects as object)).toEqual([TARGET.name]);
112+
expect((set.objects as Record<string, Record<string, unknown>>)[TARGET.name]).toMatchObject({
113+
allowRead: true,
114+
allowCreate: true,
115+
allowEdit: true,
116+
allowDelete: false,
117+
// The read depth is declared, not left to the object's sharing model.
118+
readScope: 'own',
119+
});
120+
// Never bound to every signed-in user by the scaffold.
121+
expect(set.isDefault).toBe(false);
122+
});
123+
});
124+
125+
describe('the dataset scaffold is a dataset over the bound object', () => {
126+
it('parses as a dataset named what `os g` reports it reached, over the bound object', async () => {
127+
const dataset = await loadScaffold('dataset', TARGET);
128+
expect(DatasetSchema.safeParse(dataset).success).toBe(true);
129+
expect(dataset.name).toBe(target('dataset')!.itemName(STEM));
130+
expect(dataset.object).toBe(TARGET.name);
131+
});
132+
133+
it('declares a record count, grouped by the record\'s title field', async () => {
134+
const dataset = await loadScaffold('dataset', TARGET);
135+
expect(dataset.measures).toEqual([{ name: 'record_count', label: 'Records', aggregate: 'count' }]);
136+
expect(dataset.dimensions).toEqual([{ name: TARGET.displayField, field: TARGET.displayField }]);
137+
});
138+
139+
it('an object with no title field gets no dimension, and the dataset still parses', async () => {
140+
const dataset = await loadScaffold('dataset', { ...TARGET, displayField: undefined });
141+
expect(dataset.dimensions).toEqual([]);
142+
expect(DatasetSchema.safeParse(dataset).success).toBe(true);
143+
});
144+
});

‎packages/cli/src/commands/generate.ts‎

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -742,6 +742,140 @@ const ${toCamelCase(name)}Picklist = definePicklist({
742742
export default ${toCamelCase(name)}Picklist;
743743
`,
744744
},
745+
746+
permission: {
747+
description: 'Permission set (what a signed-in user may do with an object)',
748+
/**
749+
* `src/security`, not `src/permissions`: the directory a project keeps its
750+
* access rules in, the name the example apps use for it. The type key is
751+
* the registry's, `permission` (`*.permission.ts`), and its stack key is
752+
* `singularToPlural('permission')`, `permissions` — the collection half of
753+
* that key (ADR-0090), where a permission set is the only capability
754+
* container.
755+
*/
756+
defaultDir: 'src/security',
757+
/**
758+
* A permission set whose `objects` map grants nothing gives a signed-in
759+
* user nothing, so the scaffold grants one object: the object from
760+
* `--object`, or the stack's only object, one the stack declares. The grant
761+
* is read, create and edit without delete, the shape the example apps
762+
* start a user's set from; the emitted comments name the bits to change.
763+
*
764+
* `readScope` is written, as `'own'`: on an object whose sharing model is
765+
* private (the `object` scaffold's), a read grant with no depth is what
766+
* `security-private-no-readscope` reports, because a holder then reads
767+
* only their own records and the author may not know it. `'own'` states
768+
* that same reach as a decision rather than widening it; the emitted
769+
* comment names `'org'` for the author who means every record.
770+
*
771+
* Declared through `definePermissionSet`, so the set is parsed the moment
772+
* this module loads: an unknown key (`roles`, `profiles`, `users` — none is
773+
* a field of a set) is a startup error that names where that rule lives.
774+
*
775+
* `isDefault` is left at its default (`false`) and explained instead of
776+
* written: an app-level set marked `isDefault` is bound to every signed-in
777+
* user at boot, which is a decision the author takes, not one a scaffold
778+
* takes for them.
779+
*/
780+
namesObject: true,
781+
binds: { object: 'flag' },
782+
itemName: (name: string) => toSnakeCase(name),
783+
generate: (name: string, _namespace?: string, bindings?: ScaffoldBindings) => {
784+
const object = requireBinding('permission', bindings, 'object');
785+
return `import { definePermissionSet } from '@objectstack/spec/security';
786+
787+
/**
788+
* ${toTitleCase(name)} Permission Set
789+
*
790+
* What a user holding this set may do. A user is given it by a position
791+
* that lists it in \`permissionSets\`, or by an administrator in Setup; the
792+
* set itself never names users. Sets a user holds are merged: a bit granted
793+
* by any one of them is granted.
794+
*/
795+
const ${toCamelCase(name)}PermissionSet = definePermissionSet({
796+
name: '${toSnakeCase(name)}',
797+
label: '${toTitleCase(name)}',
798+
799+
// One entry per object, keyed by its machine name. readScope is which of
800+
// the object's records a holder reads: 'own' is the ones they own (plus
801+
// records shared with them), 'org' is every record. Also: viewAllRecords
802+
// and modifyAllRecords, which reach past the object's sharing model.
803+
objects: {
804+
${tsString(object.name)}: {
805+
allowRead: true,
806+
allowCreate: true,
807+
allowEdit: true,
808+
allowDelete: false,
809+
readScope: 'own',
810+
},
811+
},
812+
813+
// isDefault: true binds this set to every signed-in user when the app
814+
// boots. Leave it off unless that is what you mean.
815+
});
816+
817+
export default ${toCamelCase(name)}PermissionSet;
818+
`;
819+
},
820+
},
821+
822+
dataset: {
823+
description: 'Analytics dataset (dimensions and measures dashboards bind to)',
824+
defaultDir: 'src/datasets',
825+
/**
826+
* The analytics semantic layer (`ui/dataset.zod.ts`, ADR-0021): a
827+
* dashboard or report widget names a dataset and picks its dimensions and
828+
* measures by name, instead of carrying its own object, field and
829+
* aggregate. Not seed data — that is the stack's `data` key.
830+
*
831+
* `object` is a BINDING (#21325): the object from `--object`, or the
832+
* stack's only object, one the stack declares. The scaffold declares the
833+
* one measure every object can answer, a record count, and groups it by
834+
* the record's title field when the object has one, so a widget has a
835+
* dimension and a measure to bind from the first build.
836+
*
837+
* Declared through `defineDataset`, which types the literal as a
838+
* `Dataset`: a bare object literal handed to the stack's `datasets` key
839+
* widens `aggregate` to `string` and fails the type check without
840+
* `as const`.
841+
*/
842+
namesObject: true,
843+
binds: { object: 'flag' },
844+
itemName: (name: string) => toSnakeCase(name),
845+
generate: (name: string, _namespace?: string, bindings?: ScaffoldBindings) => {
846+
const object = requireBinding('dataset', bindings, 'object');
847+
const dimension = object.displayField
848+
? `\n { name: ${tsString(object.displayField)}, field: ${tsString(object.displayField)} },\n `
849+
: '';
850+
return `import { defineDataset } from '@objectstack/spec/ui';
851+
852+
/**
853+
* ${toTitleCase(name)} Dataset
854+
*
855+
* The numbers a dashboard or report shows for ${tsString(object.name)}, defined once.
856+
* A widget names this dataset and picks a dimension and a measure from it by
857+
* name; it declares no object, field or aggregate of its own.
858+
*/
859+
const ${toCamelCase(name)}Dataset = defineDataset({
860+
name: '${toSnakeCase(name)}',
861+
label: '${toTitleCase(name)}',
862+
object: ${tsString(object.name)},
863+
864+
// The axes a widget groups by: a field on the object, or a path through a
865+
// lookup (\`account.region\`). Declare the fields people group by.
866+
dimensions: [${dimension}],
867+
868+
// The values a widget shows. Also: sum, avg, min and max over a numeric
869+
// field (\`{ name: 'total', aggregate: 'sum', field: 'amount' }\`).
870+
measures: [
871+
{ name: 'record_count', label: 'Records', aggregate: 'count' },
872+
],
873+
});
874+
875+
export default ${toCamelCase(name)}Dataset;
876+
`;
877+
},
878+
},
745879
};
746880

747881
/**

‎packages/create-objectstack/README.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,9 @@ my-app/
9494
├── dashboards/index.ts
9595
├── apps/index.ts
9696
├── skills/index.ts
97-
└── picklists/index.ts
97+
├── picklists/index.ts
98+
├── security/index.ts # permission sets
99+
└── datasets/index.ts # analytics datasets
98100
```
99101

100102
Next steps inside the project:

0 commit comments

Comments
 (0)