@diagonal-hq/cli 0.9.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -325,6 +325,60 @@ export default defineResource({
325
325
  - Provisioning can create a field, for example `accounting_entity`. The files cannot declare a field with the same key later. The deploy refuses it until you delete the field in the resource builder or use another key.
326
326
  - A capability change in the resource builder is drift. The next deploy reports it and restores the capability from the files.
327
327
 
328
+ ## Policies
329
+
330
+ A policy grants access to the records of its resource. Each policy option maps to one option of a stored policy:
331
+
332
+ ```ts
333
+ import { Resources } from '@app/generated/resources';
334
+
335
+ export default defineResource({
336
+ name: 'Posts',
337
+ singularName: 'Post',
338
+ fields: {
339
+ title: field.text({ required: true }),
340
+ body: field.text(),
341
+ author: field.relation({ resource: Resources.Members.slug, type: 'belongs_to' })
342
+ },
343
+ policies: [
344
+ {
345
+ name: 'Visitors read titles',
346
+ scope: ['index', 'show'],
347
+ access: 'public',
348
+ fields: ['id', 'title']
349
+ },
350
+ {
351
+ name: 'Authors edit their posts',
352
+ scope: ['update', 'destroy'],
353
+ resource: Resources.Members.slug,
354
+ filter: {
355
+ operator: 'and',
356
+ conditions: [
357
+ {
358
+ field: 'author.id',
359
+ operator: '=',
360
+ value: { $type: 'user.current', $value: { key: 'id' } }
361
+ }
362
+ ]
363
+ },
364
+ fields: ['title', 'body']
365
+ }
366
+ ]
367
+ });
368
+ ```
369
+
370
+ - `scope` is `'all'` or a list of operations: `index`, `show`, `count`, `aggregate`, `store`, `storeMany`, `update`, `destroy`, `restore`, and `validate`.
371
+ - `access` is `'public'` or `'protected'`. The default is `'protected'`. A public policy grants access to every visitor, and it cannot set `resource` or `authorizer`.
372
+ - `resource` is the resource that members sign in as, as `Resources.<Name>.slug`. The resource must have the `authenticatable` capability. A protected policy without `resource` grants access only to system administrators.
373
+ - `authorizer` is a filter tree that the member's own record must match, for example `{ operator: 'and', conditions: [{ field: 'permission_slugs', operator: 'in', value: ['moderate'] }] }`.
374
+ - `filter` is a filter tree that limits the records that the policy covers. Compare a relation to the signed-in member with `<relation>.id` and the resolver `{ $type: 'user.current', $value: { key: 'id' } }`.
375
+ - `fields` is an allow-list of field keys. A key can be a relation path, such as `author.name`. An item can also be `{ key, condition }`, where `condition` is a resolver that returns true when the field shows. A field that the list leaves out is hidden from reads and refused on writes. Without `fields`, the policy covers every field.
376
+ - `enabled: false` keeps the policy but grants nothing. The default is `true`.
377
+
378
+ A filter tree has the shape of a record search filter: `{ operator: 'and' | 'or' | 'nor', conditions }`. Each condition is `{ field, operator, value, case_insensitive }` or a nested group. The policy id comes from the resource and the policy name, so each policy of a resource has a different name.
379
+
380
+ The build checks the shape of each option, the filter operators, and the resource that members sign in as. The deploy checks each policy with the rules of the policy API against the deployed schema: the filter paths, the authorizer paths, the field keys, and the field conditions. A policy that fails rejects the deploy, and the previous deployment keeps serving. A field that capability provisioning creates, such as the roles relation of an Authenticatable resource, exists only after the first deploy of that capability.
381
+
328
382
  A workflow script reads the capabilities of each resource from `@diagonal/workflow/workspace`. An input that needs a capability, such as the `resource` of `notification.setConsent`, accepts only a resource that declares it.
329
383
 
330
384
  ## Application asset references
package/dist/cli.mjs CHANGED
@@ -101,7 +101,7 @@ var require_jsesc = __commonJS({
101
101
  var isBuffer = (value) => {
102
102
  return typeof Buffer === "function" && Buffer.isBuffer(value);
103
103
  };
104
- var isObject2 = (value) => {
104
+ var isObject = (value) => {
105
105
  return toString.call(value) == "[object Object]";
106
106
  };
107
107
  var isString = (value) => {
@@ -261,7 +261,7 @@ var require_jsesc = __commonJS({
261
261
  return JSON.stringify(Number(argument));
262
262
  }
263
263
  return argument + "n";
264
- } else if (!isObject2(argument)) {
264
+ } else if (!isObject(argument)) {
265
265
  if (json) {
266
266
  return JSON.stringify(argument) || "null";
267
267
  }
@@ -183036,7 +183036,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")}
183036
183036
  return void 0;
183037
183037
  }
183038
183038
  }
183039
- function getJSDocParamAnnotation(paramName, initializer, dotDotDotToken, isJs, isObject2, isSnippet, checker, options2, preferences, tabstopCounter) {
183039
+ function getJSDocParamAnnotation(paramName, initializer, dotDotDotToken, isJs, isObject, isSnippet, checker, options2, preferences, tabstopCounter) {
183040
183040
  if (isSnippet) {
183041
183041
  Debug.assertIsDefined(tabstopCounter);
183042
183042
  }
@@ -183048,7 +183048,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")}
183048
183048
  }
183049
183049
  if (isJs) {
183050
183050
  let type = "*";
183051
- if (isObject2) {
183051
+ if (isObject) {
183052
183052
  Debug.assert(!dotDotDotToken, `Cannot annotate a rest parameter with type 'Object'.`);
183053
183053
  type = "Object";
183054
183054
  } else {
@@ -183084,7 +183084,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")}
183084
183084
  type = `\${${tabstopCounter.tabstop++}:${type}}`;
183085
183085
  }
183086
183086
  }
183087
- const dotDotDot = !isObject2 && dotDotDotToken ? "..." : "";
183087
+ const dotDotDot = !isObject && dotDotDotToken ? "..." : "";
183088
183088
  const description3 = isSnippet ? `\${${tabstopCounter.tabstop++}}` : "";
183089
183089
  return `@param {${dotDotDot}${type}} ${paramName} ${description3}`;
183090
183090
  } else {
@@ -260949,14 +260949,14 @@ var typescript = (superClass) => class TypeScriptParserMixin extends superClass
260949
260949
  const node = this.startNode();
260950
260950
  node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false);
260951
260951
  let seenOptionalElement = false;
260952
- node.elementTypes.forEach((elementNode3) => {
260952
+ node.elementTypes.forEach((elementNode2) => {
260953
260953
  const {
260954
260954
  type
260955
- } = elementNode3;
260956
- if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode3.optional)) {
260957
- this.raise(TSErrors.OptionalTypeBeforeRequired, elementNode3);
260955
+ } = elementNode2;
260956
+ if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode2.optional)) {
260957
+ this.raise(TSErrors.OptionalTypeBeforeRequired, elementNode2);
260958
260958
  }
260959
- seenOptionalElement ||= type === "TSNamedTupleMember" && elementNode3.optional || type === "TSOptionalType";
260959
+ seenOptionalElement ||= type === "TSNamedTupleMember" && elementNode2.optional || type === "TSOptionalType";
260960
260960
  });
260961
260961
  return this.finishNode(node, "TSTupleType");
260962
260962
  }
@@ -264334,6 +264334,33 @@ function staticObject(node, options2 = {}) {
264334
264334
  }
264335
264335
  return { value, nodes };
264336
264336
  }
264337
+ function propertyNode(objectNode, key) {
264338
+ const node = objectNode?.value ?? objectNode;
264339
+ if (node?.type !== "ObjectExpression") {
264340
+ return objectNode;
264341
+ }
264342
+ return node.properties.find((property) => (property.key.name ?? property.key.value) === key) ?? objectNode;
264343
+ }
264344
+ function elementNode(listNode, position2) {
264345
+ const node = listNode?.value ?? listNode;
264346
+ return node?.type === "ArrayExpression" ? node.elements[position2] ?? listNode : listNode;
264347
+ }
264348
+ function isPlainObject(value) {
264349
+ return value !== null && typeof value === "object" && !Array.isArray(value);
264350
+ }
264351
+ function requireString(value, key, node, { optional = false } = {}) {
264352
+ const item = value[key];
264353
+ if (item === void 0 || item === null) {
264354
+ if (optional) {
264355
+ return null;
264356
+ }
264357
+ throw new SourceError(`"${key}" is required`, node);
264358
+ }
264359
+ if (typeof item !== "string" || item === "") {
264360
+ throw new SourceError(`"${key}" must be a non-empty string`, node);
264361
+ }
264362
+ return item;
264363
+ }
264337
264364
 
264338
264365
  // scripts/lib/runtime-build/assets.mjs
264339
264366
  var ASSET_KEY = /^[a-z][A-Za-z0-9]*$/;
@@ -267398,25 +267425,11 @@ var capability_catalog_default = {
267398
267425
 
267399
267426
  // scripts/lib/runtime-build/capabilities.mjs
267400
267427
  var FIELD_REFERENCE_TYPES = /* @__PURE__ */ new Set(["field_reference", "resource_field_key_reference"]);
267401
- function isObject(value) {
267402
- return value !== null && typeof value === "object" && !Array.isArray(value);
267403
- }
267404
- function propertyNode(objectNode, key) {
267405
- const node = objectNode?.value ?? objectNode;
267406
- if (node?.type !== "ObjectExpression") {
267407
- return objectNode;
267408
- }
267409
- return node.properties.find((property) => (property.key.name ?? property.key.value) === key) ?? objectNode;
267410
- }
267411
- function elementNode(listNode, position2) {
267412
- const node = listNode?.value ?? listNode;
267413
- return node?.type === "ArrayExpression" ? node.elements[position2] ?? listNode : listNode;
267414
- }
267415
267428
  function readCapabilities(capabilities, node) {
267416
267429
  if (capabilities === void 0) {
267417
267430
  return {};
267418
267431
  }
267419
- if (!isObject(capabilities)) {
267432
+ if (!isPlainObject(capabilities)) {
267420
267433
  throw new SourceError('"capabilities" must be an object keyed by capability', node);
267421
267434
  }
267422
267435
  for (const [identifier4, settings] of Object.entries(capabilities)) {
@@ -267431,7 +267444,7 @@ function readCapabilities(capabilities, node) {
267431
267444
  capabilityNode
267432
267445
  );
267433
267446
  }
267434
- if (!isObject(settings)) {
267447
+ if (!isPlainObject(settings)) {
267435
267448
  throw new SourceError(
267436
267449
  `Capability "${identifier4}" must be an object of settings`,
267437
267450
  capabilityNode
@@ -267513,7 +267526,7 @@ function checkSetting(context, setting, value, label, node) {
267513
267526
  return;
267514
267527
  }
267515
267528
  if (setting.properties !== null) {
267516
- if (!isObject(value)) {
267529
+ if (!isPlainObject(value)) {
267517
267530
  problems.push({ message: `${label} must be an object`, node });
267518
267531
  return;
267519
267532
  }
@@ -279666,7 +279679,7 @@ var objectToString = Function.call.bind(Object.prototype.toString);
279666
279679
  function isRegExp(value) {
279667
279680
  return objectToString(value) === "[object RegExp]";
279668
279681
  }
279669
- function isPlainObject(value) {
279682
+ function isPlainObject2(value) {
279670
279683
  if (typeof value !== "object" || value === null || Object.prototype.toString.call(value) !== "[object Object]") {
279671
279684
  return false;
279672
279685
  }
@@ -279719,7 +279732,7 @@ function valueToNode(value) {
279719
279732
  if (Array.isArray(value)) {
279720
279733
  return arrayExpression(value.map(valueToNode));
279721
279734
  }
279722
- if (isPlainObject(value)) {
279735
+ if (isPlainObject2(value)) {
279723
279736
  const props = [];
279724
279737
  for (const key of Object.keys(value)) {
279725
279738
  let nodeKey, computed = false;
@@ -296164,7 +296177,7 @@ function lintUnit(unit, catalogs) {
296164
296177
  return [];
296165
296178
  }
296166
296179
 
296167
- // scripts/lib/runtime-build/resources.mjs
296180
+ // scripts/lib/runtime-build/policies.mjs
296168
296181
  init_define_globalThis_DIAGONAL_SDK_RUNTIME();
296169
296182
 
296170
296183
  // scripts/lib/runtime-build/fields.mjs
@@ -297839,6 +297852,44 @@ var field_catalog_default = {
297839
297852
  "update_many",
297840
297853
  "upsert",
297841
297854
  "upsert_many"
297855
+ ],
297856
+ filter_operators: [
297857
+ "all",
297858
+ "between",
297859
+ "contains",
297860
+ "elem_match",
297861
+ "ends_with",
297862
+ "=",
297863
+ "exists",
297864
+ ">",
297865
+ ">=",
297866
+ "has_value",
297867
+ "in",
297868
+ "is",
297869
+ "is_not",
297870
+ "is_not_null",
297871
+ "is_null",
297872
+ "<",
297873
+ "<=",
297874
+ "missing_value",
297875
+ "mod",
297876
+ "not",
297877
+ "!=",
297878
+ "not_exists",
297879
+ "not_in",
297880
+ "regex",
297881
+ "search",
297882
+ "starts_with"
297883
+ ],
297884
+ record_meta_fields: [
297885
+ "id",
297886
+ "workspace_id",
297887
+ "resource_id",
297888
+ "__meta",
297889
+ "created_at",
297890
+ "updated_at",
297891
+ "deleted_at",
297892
+ "cascade_key"
297842
297893
  ]
297843
297894
  };
297844
297895
 
@@ -297889,9 +297940,6 @@ function optionNode(builder2, ...path) {
297889
297940
  }
297890
297941
  return node;
297891
297942
  }
297892
- function isPlainObject2(value) {
297893
- return value !== null && typeof value === "object" && !Array.isArray(value);
297894
- }
297895
297943
  function humanize2(key) {
297896
297944
  const words = key.replaceAll("_", " ");
297897
297945
  return words.charAt(0).toUpperCase() + words.slice(1);
@@ -297911,7 +297959,7 @@ function resolverOption(builder2, key, fieldKey) {
297911
297959
  if (value === void 0) {
297912
297960
  return null;
297913
297961
  }
297914
- if (!isPlainObject2(value) || typeof value.$type !== "string" || value.$type === "") {
297962
+ if (!isPlainObject(value) || typeof value.$type !== "string" || value.$type === "") {
297915
297963
  throw new SourceError(
297916
297964
  `"${key}" of field "${fieldKey}" must be a resolver: { $type: '<task>', $value: {...} }`,
297917
297965
  optionNode(builder2, key)
@@ -297951,7 +297999,7 @@ function checkValue(entry, value, describe, node) {
297951
297999
  }
297952
298000
  }
297953
298001
  function checkUiSettings(ui, typeCatalog, describe, nodeAt) {
297954
- if (!isPlainObject2(ui)) {
298002
+ if (!isPlainObject(ui)) {
297955
298003
  throw new SourceError(`${describe}.ui must be an object`, nodeAt());
297956
298004
  }
297957
298005
  for (const [key, value] of Object.entries(ui)) {
@@ -297967,7 +298015,7 @@ function checkUiSettings(ui, typeCatalog, describe, nodeAt) {
297967
298015
  }
297968
298016
  function selectOptions(options2, fieldKey, node) {
297969
298017
  if (!Array.isArray(options2) || options2.length === 0 || options2.some(
297970
- (option) => !isPlainObject2(option) || typeof option.label !== "string" || typeof option.value !== "string" || Object.keys(option).some((key) => !OPTION_KEYS.has(key)) || option.color !== void 0 && option.color !== null && typeof option.color !== "string"
298018
+ (option) => !isPlainObject(option) || typeof option.label !== "string" || typeof option.value !== "string" || Object.keys(option).some((key) => !OPTION_KEYS.has(key)) || option.color !== void 0 && option.color !== null && typeof option.color !== "string"
297971
298019
  )) {
297972
298020
  throw new SourceError(
297973
298021
  `field.select "${fieldKey}" needs "options": [{ label, value, color? }] with string labels and values`,
@@ -297989,7 +298037,7 @@ function checkInverse(inverse, fieldKey, relationSettings2, nodeAt) {
297989
298037
  if (inverse === null) {
297990
298038
  return;
297991
298039
  }
297992
- if (!isPlainObject2(inverse)) {
298040
+ if (!isPlainObject(inverse)) {
297993
298041
  throw new SourceError(`settings.inverse of field "${fieldKey}" must be an object`, nodeAt());
297994
298042
  }
297995
298043
  for (const key of Object.keys(inverse)) {
@@ -298018,7 +298066,7 @@ function checkInverse(inverse, fieldKey, relationSettings2, nodeAt) {
298018
298066
  if (inverse.settings === void 0) {
298019
298067
  return;
298020
298068
  }
298021
- if (!isPlainObject2(inverse.settings)) {
298069
+ if (!isPlainObject(inverse.settings)) {
298022
298070
  throw new SourceError(
298023
298071
  `settings.inverse.settings of field "${fieldKey}" must be an object`,
298024
298072
  nodeAt("settings")
@@ -298051,7 +298099,7 @@ function buildSettings(key, builder2, entry, typeCatalog) {
298051
298099
  const shorthandFor = Object.fromEntries(
298052
298100
  Object.entries(entry.shorthands).map(([option, setting]) => [setting, option])
298053
298101
  );
298054
- if (!isPlainObject2(authored)) {
298102
+ if (!isPlainObject(authored)) {
298055
298103
  throw new SourceError(`"settings" of field "${key}" must be an object`, nodeAt());
298056
298104
  }
298057
298105
  for (const [setting, value] of Object.entries(authored)) {
@@ -298238,7 +298286,7 @@ function buildField(key, builder2, keyNode) {
298238
298286
  return relationNode === null ? field2 : { ...field2, relationNode };
298239
298287
  }
298240
298288
 
298241
- // scripts/lib/runtime-build/resources.mjs
298289
+ // scripts/lib/runtime-build/policies.mjs
298242
298290
  var POLICY_SCOPES = [
298243
298291
  "index",
298244
298292
  "show",
@@ -298252,35 +298300,200 @@ var POLICY_SCOPES = [
298252
298300
  "validate"
298253
298301
  ];
298254
298302
  var POLICY_ACCESS = /* @__PURE__ */ new Set(["public", "protected"]);
298255
- var RESOURCE_KEYS = /* @__PURE__ */ new Set([
298303
+ var POLICY_KEYS = /* @__PURE__ */ new Set([
298256
298304
  "name",
298257
- "singularName",
298258
- "displayField",
298259
- "searchableFields",
298260
- "fieldOrder",
298261
- "fields",
298262
- "indexes",
298263
- "embeddings",
298264
- "dataApi",
298265
- "static",
298266
- "policies",
298267
- "capabilities"
298305
+ "scope",
298306
+ "access",
298307
+ "description",
298308
+ "enabled",
298309
+ "resource",
298310
+ "authorizer",
298311
+ "filter",
298312
+ "fields"
298268
298313
  ]);
298269
- var INDEX_KEYS = /* @__PURE__ */ new Set(["fields", "unique"]);
298270
- var EMBEDDINGS_KEYS = /* @__PURE__ */ new Set(["enabled", "fields"]);
298271
- var DEFAULT_SEARCHABLE_TYPES = /* @__PURE__ */ new Set(["text", "markdown"]);
298272
- function requireString(value, key, node, { optional = false } = {}) {
298273
- const item = value[key];
298274
- if (item === void 0 || item === null) {
298275
- if (optional) {
298276
- return null;
298314
+ var PUBLIC_REFUSED_KEYS = ["resource", "authorizer"];
298315
+ var GROUP_OPERATORS = /* @__PURE__ */ new Set(["and", "or", "nor"]);
298316
+ var GROUP_KEYS = /* @__PURE__ */ new Set(["operator", "conditions"]);
298317
+ var CONDITION_KEYS = /* @__PURE__ */ new Set(["field", "operator", "value", "case_insensitive"]);
298318
+ var FILTER_OPERATORS = new Set(FIELD_CATALOG.filter_operators);
298319
+ function isResolver(value) {
298320
+ return isPlainObject(value) && typeof value.$type === "string" && value.$type !== "";
298321
+ }
298322
+ function buildScope(policy, label, node) {
298323
+ if (policy.scope === "all") {
298324
+ return [...POLICY_SCOPES];
298325
+ }
298326
+ if (Array.isArray(policy.scope) && policy.scope.length > 0 && policy.scope.every((item) => POLICY_SCOPES.includes(item))) {
298327
+ return [...new Set(policy.scope)];
298328
+ }
298329
+ throw new SourceError(
298330
+ `${label} scope must be "all" or a list of: ${POLICY_SCOPES.join(", ")}`,
298331
+ propertyNode(node, "scope")
298332
+ );
298333
+ }
298334
+ function checkFilterGroup(group, path, node) {
298335
+ if (!isPlainObject(group)) {
298336
+ throw new SourceError(`${path} must be { operator, conditions }`, node);
298337
+ }
298338
+ for (const key of Object.keys(group)) {
298339
+ if (!GROUP_KEYS.has(key)) {
298340
+ throw new SourceError(
298341
+ `${path} has an unknown option "${key}". Use operator or conditions`,
298342
+ propertyNode(node, key)
298343
+ );
298277
298344
  }
298278
- throw new SourceError(`"${key}" is required`, node);
298279
298345
  }
298280
- if (typeof item !== "string" || item === "") {
298281
- throw new SourceError(`"${key}" must be a non-empty string`, node);
298346
+ if (!GROUP_OPERATORS.has(group.operator)) {
298347
+ throw new SourceError(
298348
+ `${path}.operator must be "and", "or", or "nor"`,
298349
+ propertyNode(node, "operator")
298350
+ );
298282
298351
  }
298283
- return item;
298352
+ const conditionsNode = propertyNode(node, "conditions");
298353
+ if (!Array.isArray(group.conditions) || group.conditions.length === 0) {
298354
+ throw new SourceError(`${path}.conditions must be a non-empty list`, conditionsNode);
298355
+ }
298356
+ group.conditions.forEach((condition, position2) => {
298357
+ const conditionPath = `${path}.conditions[${position2}]`;
298358
+ const conditionNode = elementNode(conditionsNode, position2);
298359
+ if (isPlainObject(condition) && Object.hasOwn(condition, "conditions")) {
298360
+ checkFilterGroup(condition, conditionPath, conditionNode);
298361
+ return;
298362
+ }
298363
+ checkFilterCondition(condition, conditionPath, conditionNode);
298364
+ });
298365
+ }
298366
+ function checkFilterCondition(condition, path, node) {
298367
+ if (!isPlainObject(condition)) {
298368
+ throw new SourceError(`${path} must be { field, operator, value } or a nested group`, node);
298369
+ }
298370
+ for (const key of Object.keys(condition)) {
298371
+ if (!CONDITION_KEYS.has(key)) {
298372
+ throw new SourceError(
298373
+ `${path} has an unknown option "${key}". Use field, operator, value, or case_insensitive`,
298374
+ propertyNode(node, key)
298375
+ );
298376
+ }
298377
+ }
298378
+ if (typeof condition.field !== "string" || condition.field === "") {
298379
+ throw new SourceError(`${path}.field must be a field key or path`, propertyNode(node, "field"));
298380
+ }
298381
+ if (!FILTER_OPERATORS.has(condition.operator)) {
298382
+ throw new SourceError(
298383
+ `${path}.operator must be one of: ${FIELD_CATALOG.filter_operators.join(", ")}`,
298384
+ propertyNode(node, "operator")
298385
+ );
298386
+ }
298387
+ if (condition.case_insensitive !== void 0 && typeof condition.case_insensitive !== "boolean") {
298388
+ throw new SourceError(
298389
+ `${path}.case_insensitive must be true or false`,
298390
+ propertyNode(node, "case_insensitive")
298391
+ );
298392
+ }
298393
+ }
298394
+ function buildFilter(policy, key, label, node) {
298395
+ const value = policy[key];
298396
+ if (value === void 0 || value === null) {
298397
+ return null;
298398
+ }
298399
+ checkFilterGroup(value, `${label} ${key}`, propertyNode(node, key));
298400
+ return value;
298401
+ }
298402
+ function buildFields(policy, label, node) {
298403
+ if (policy.fields === void 0 || policy.fields === null) {
298404
+ return null;
298405
+ }
298406
+ const fieldsNode = propertyNode(node, "fields");
298407
+ if (!Array.isArray(policy.fields)) {
298408
+ throw new SourceError(
298409
+ `${label} fields must be a list of field keys or { key, condition }`,
298410
+ fieldsNode
298411
+ );
298412
+ }
298413
+ const seen = /* @__PURE__ */ new Set();
298414
+ return policy.fields.map((item, position2) => {
298415
+ const itemNode = elementNode(fieldsNode, position2);
298416
+ const rule = typeof item === "string" ? { key: item } : item;
298417
+ if (!isPlainObject(rule) || typeof rule.key !== "string" || rule.key === "" || Object.keys(rule).some((key) => key !== "key" && key !== "condition")) {
298418
+ throw new SourceError(
298419
+ `${label} fields must be a list of field keys or { key, condition }`,
298420
+ itemNode
298421
+ );
298422
+ }
298423
+ if (rule.condition !== void 0 && rule.condition !== null && !isResolver(rule.condition)) {
298424
+ throw new SourceError(
298425
+ `${label} field "${rule.key}" condition must be a resolver, for example { $type: 'user.current' }`,
298426
+ itemNode
298427
+ );
298428
+ }
298429
+ if (seen.has(rule.key)) {
298430
+ throw new SourceError(`${label} fields list "${rule.key}" twice`, itemNode);
298431
+ }
298432
+ seen.add(rule.key);
298433
+ return rule.condition === void 0 || rule.condition === null ? { key: rule.key } : { key: rule.key, condition: rule.condition };
298434
+ });
298435
+ }
298436
+ function buildPolicy(policy, node) {
298437
+ if (!isPlainObject(policy)) {
298438
+ throw new SourceError("Each policy must be an object", node);
298439
+ }
298440
+ const name = requireString(policy, "name", propertyNode(node, "name"));
298441
+ const label = `Policy "${name}"`;
298442
+ for (const key of Object.keys(policy)) {
298443
+ if (!POLICY_KEYS.has(key)) {
298444
+ throw new SourceError(
298445
+ `${label} has an unknown option "${key}". Use ${[...POLICY_KEYS].join(", ")}`,
298446
+ propertyNode(node, key)
298447
+ );
298448
+ }
298449
+ }
298450
+ const access = policy.access ?? "protected";
298451
+ if (!POLICY_ACCESS.has(access)) {
298452
+ throw new SourceError(
298453
+ `${label} access must be "public" or "protected"`,
298454
+ propertyNode(node, "access")
298455
+ );
298456
+ }
298457
+ if (access === "public") {
298458
+ const refused = PUBLIC_REFUSED_KEYS.find(
298459
+ (key) => policy[key] !== void 0 && policy[key] !== null
298460
+ );
298461
+ if (refused !== void 0) {
298462
+ throw new SourceError(
298463
+ `${label} is public, so it cannot set "${refused}". Remove it, or make the policy protected`,
298464
+ propertyNode(node, refused)
298465
+ );
298466
+ }
298467
+ }
298468
+ const description = policy.description ?? null;
298469
+ if (description !== null && typeof description !== "string") {
298470
+ throw new SourceError(
298471
+ `${label} description must be a string`,
298472
+ propertyNode(node, "description")
298473
+ );
298474
+ }
298475
+ if (policy.enabled !== void 0 && typeof policy.enabled !== "boolean") {
298476
+ throw new SourceError(`${label} enabled must be true or false`, propertyNode(node, "enabled"));
298477
+ }
298478
+ const resource = policy.resource ?? null;
298479
+ if (resource !== null && (typeof resource !== "string" || resource === "")) {
298480
+ throw new SourceError(
298481
+ `${label} resource must be Resources.<Name>.slug`,
298482
+ propertyNode(node, "resource")
298483
+ );
298484
+ }
298485
+ return {
298486
+ name,
298487
+ scope: buildScope(policy, label, node),
298488
+ access,
298489
+ description,
298490
+ enabled: policy.enabled ?? true,
298491
+ resource,
298492
+ authorizer: buildFilter(policy, "authorizer", label, node),
298493
+ filter: buildFilter(policy, "filter", label, node),
298494
+ fields: buildFields(policy, label, node),
298495
+ resourceNode: resource === null ? void 0 : propertyNode(node, "resource")
298496
+ };
298284
298497
  }
298285
298498
  function buildPolicies(policies, node) {
298286
298499
  if (policies === void 0) {
@@ -298289,37 +298502,68 @@ function buildPolicies(policies, node) {
298289
298502
  if (!Array.isArray(policies)) {
298290
298503
  throw new SourceError('"policies" must be an array', node);
298291
298504
  }
298505
+ const names2 = /* @__PURE__ */ new Set();
298292
298506
  return policies.map((policy, position2) => {
298293
- const elementNode3 = node.value.elements?.[position2] ?? node;
298294
- if (policy === null || typeof policy !== "object" || Array.isArray(policy)) {
298295
- throw new SourceError("Each policy must be an object", elementNode3);
298296
- }
298297
- const name = requireString(policy, "name", elementNode3);
298298
- const access = requireString(policy, "access", elementNode3);
298299
- if (!POLICY_ACCESS.has(access)) {
298300
- throw new SourceError(`Policy "${name}" access must be "public" or "protected"`, elementNode3);
298301
- }
298302
- let scope2;
298303
- if (policy.scope === "all") {
298304
- scope2 = [...POLICY_SCOPES];
298305
- } else if (Array.isArray(policy.scope) && policy.scope.length > 0 && policy.scope.every((item) => POLICY_SCOPES.includes(item))) {
298306
- scope2 = [...new Set(policy.scope)];
298307
- } else {
298308
- throw new SourceError(
298309
- `Policy "${name}" scope must be "all" or a list of: ${POLICY_SCOPES.join(", ")}`,
298310
- elementNode3
298311
- );
298312
- }
298313
- const description = policy.description ?? null;
298314
- if (description !== null && typeof description !== "string") {
298315
- throw new SourceError(`Policy "${name}" description must be a string`, elementNode3);
298507
+ const policyNode = elementNode(node, position2);
298508
+ const built = buildPolicy(policy, policyNode);
298509
+ if (names2.has(built.name)) {
298510
+ throw new SourceError(`Two policies are named "${built.name}"`, policyNode);
298316
298511
  }
298317
- return { name, scope: scope2, access, description };
298512
+ names2.add(built.name);
298513
+ return built;
298318
298514
  });
298319
298515
  }
298320
- function elementNode2(node, position2) {
298321
- return node?.value?.elements?.[position2] ?? node;
298516
+ function checkPolicyResources(resources, platformSlugs, names2, diagnostics) {
298517
+ const resourcesBySlug = new Map(resources.map((resource) => [resource.slug, resource]));
298518
+ for (const resource of resources) {
298519
+ for (const policy of resource.policies) {
298520
+ if (policy.resource === null || platformSlugs.has(policy.resource)) {
298521
+ continue;
298522
+ }
298523
+ const target = resourcesBySlug.get(policy.resource);
298524
+ const label = `Policy "${policy.name}" resource`;
298525
+ if (target === void 0) {
298526
+ diagnostics.push(
298527
+ diagnosticAt(
298528
+ resource.path,
298529
+ policy.resourceNode,
298530
+ `${label}: ${referenceProblem(policy.resource, resources, names2).message}`
298531
+ )
298532
+ );
298533
+ continue;
298534
+ }
298535
+ if (!Object.hasOwn(target.capabilities, "authenticatable")) {
298536
+ diagnostics.push(
298537
+ diagnosticAt(
298538
+ resource.path,
298539
+ policy.resourceNode,
298540
+ `${label}: "${policy.resource}" does not declare the authenticatable capability, so no member signs in as it`
298541
+ )
298542
+ );
298543
+ }
298544
+ }
298545
+ }
298322
298546
  }
298547
+
298548
+ // scripts/lib/runtime-build/resources.mjs
298549
+ init_define_globalThis_DIAGONAL_SDK_RUNTIME();
298550
+ var RESOURCE_KEYS = /* @__PURE__ */ new Set([
298551
+ "name",
298552
+ "singularName",
298553
+ "displayField",
298554
+ "searchableFields",
298555
+ "fieldOrder",
298556
+ "fields",
298557
+ "indexes",
298558
+ "embeddings",
298559
+ "dataApi",
298560
+ "static",
298561
+ "policies",
298562
+ "capabilities"
298563
+ ]);
298564
+ var INDEX_KEYS = /* @__PURE__ */ new Set(["fields", "unique"]);
298565
+ var EMBEDDINGS_KEYS = /* @__PURE__ */ new Set(["enabled", "fields"]);
298566
+ var DEFAULT_SEARCHABLE_TYPES = /* @__PURE__ */ new Set(["text", "markdown"]);
298323
298567
  function stringList(value, key, node) {
298324
298568
  if (!Array.isArray(value)) {
298325
298569
  throw new SourceError(`"${key}" must be a list of strings`, node);
@@ -298327,10 +298571,10 @@ function stringList(value, key, node) {
298327
298571
  const seen = /* @__PURE__ */ new Set();
298328
298572
  value.forEach((item, position2) => {
298329
298573
  if (typeof item !== "string" || item === "") {
298330
- throw new SourceError(`"${key}" must be a list of strings`, elementNode2(node, position2));
298574
+ throw new SourceError(`"${key}" must be a list of strings`, elementNode(node, position2));
298331
298575
  }
298332
298576
  if (seen.has(item)) {
298333
- throw new SourceError(`"${key}" lists "${item}" twice`, elementNode2(node, position2));
298577
+ throw new SourceError(`"${key}" lists "${item}" twice`, elementNode(node, position2));
298334
298578
  }
298335
298579
  seen.add(item);
298336
298580
  });
@@ -298345,7 +298589,7 @@ function buildIndexes(indexes, node, fieldsByKey) {
298345
298589
  }
298346
298590
  const patterns = /* @__PURE__ */ new Set();
298347
298591
  return indexes.map((index3, position2) => {
298348
- const indexNode = elementNode2(node, position2);
298592
+ const indexNode = elementNode(node, position2);
298349
298593
  if (index3 === null || typeof index3 !== "object" || Array.isArray(index3) || !Array.isArray(index3.fields) || index3.fields.length === 0) {
298350
298594
  throw new SourceError("Each index must be { fields: [...], unique?: boolean }", indexNode);
298351
298595
  }
@@ -298385,7 +298629,7 @@ function orderFields(fields, fieldOrder, node) {
298385
298629
  if (!fieldsByKey.has(key)) {
298386
298630
  throw new SourceError(
298387
298631
  `fieldOrder names "${key}", which is not a field of this resource`,
298388
- elementNode2(node, position2)
298632
+ elementNode(node, position2)
298389
298633
  );
298390
298634
  }
298391
298635
  });
@@ -298659,7 +298903,11 @@ function checkFieldPaths(resources, diagnostics) {
298659
298903
  }
298660
298904
  function withoutBuildNodes(resource) {
298661
298905
  const { pathNodes: _pathNodes, ...rest } = resource;
298662
- return { ...rest, fields: rest.fields.map(({ relationNode: _relationNode, ...field2 }) => field2) };
298906
+ return {
298907
+ ...rest,
298908
+ fields: rest.fields.map(({ relationNode: _relationNode, ...field2 }) => field2),
298909
+ policies: rest.policies.map(({ resourceNode: _resourceNode, ...policy }) => policy)
298910
+ };
298663
298911
  }
298664
298912
 
298665
298913
  // scripts/lib/runtime-build/sdk-packages.mjs
@@ -300956,9 +301204,6 @@ function propertyNodes(node) {
300956
301204
  }
300957
301205
  return nodes;
300958
301206
  }
300959
- function isPlainObject3(value) {
300960
- return value !== null && typeof value === "object" && !Array.isArray(value);
300961
- }
300962
301207
  function listOf(values) {
300963
301208
  return values.map((value) => `'${value}'`).join(", ");
300964
301209
  }
@@ -301058,7 +301303,7 @@ function readWorkflowConfig(path, configNode, context) {
301058
301303
  report(error.node, error.message);
301059
301304
  return { config: null, diagnostics };
301060
301305
  }
301061
- if (!isPlainObject3(value)) {
301306
+ if (!isPlainObject(value)) {
301062
301307
  report(configNode, "The config must be an object literal");
301063
301308
  return { config: null, diagnostics };
301064
301309
  }
@@ -301120,7 +301365,7 @@ function oneOf(trigger, key, allowed, at, report) {
301120
301365
  return item;
301121
301366
  }
301122
301367
  function readTrigger(trigger, triggerNode, context, report) {
301123
- if (!isPlainObject3(trigger)) {
301368
+ if (!isPlainObject(trigger)) {
301124
301369
  report(triggerNode, `"trigger" is required: { type: ${listOf(Object.keys(TRIGGERS))}, ... }`);
301125
301370
  return null;
301126
301371
  }
@@ -301293,7 +301538,7 @@ function readRunAs(runAs, node, trigger, context, report) {
301293
301538
  }
301294
301539
  return { mode: "session" };
301295
301540
  }
301296
- if (!isPlainObject3(runAs)) {
301541
+ if (!isPlainObject(runAs)) {
301297
301542
  report(node, "runAs must be 'system', 'session', or { resource, record }");
301298
301543
  return null;
301299
301544
  }
@@ -301954,6 +302199,7 @@ function buildWorkspace(root, { assetCatalog = null, writeSource = false } = {})
301954
302199
  addInverseFields(output.resources, diagnostics);
301955
302200
  checkFieldPaths(output.resources, diagnostics);
301956
302201
  checkCapabilities(output.resources, platformSlugs, diagnostics);
302202
+ checkPolicyResources(output.resources, platformSlugs, names2, diagnostics);
301957
302203
  }
301958
302204
  output.resources = output.resources.map(withoutBuildNodes);
301959
302205
  writeGeneratedResources(root, names2, [...output.resources, ...output.platform_resources]);
@@ -1,5 +1,5 @@
1
1
  // Generated by `artisan app:generate-custom-typescript` from VariableType. Do not edit.
2
- // The field builders of defineResource, one for each resource field type, and the data API endpoints.
2
+ // The field builders of defineResource, one for each resource field type, the data API endpoints, the filter operators, and the record meta fields.
3
3
 
4
4
  import type { StaticValue } from './index';
5
5
 
@@ -8,6 +8,12 @@ export type FieldType = "boolean" | "color" | "content" | "date" | "datetime" |
8
8
  /** A switch of `dataApi.endpoints` in defineResource. */
9
9
  export type DataApiEndpoint = "analytics_distribution" | "analytics_kpi" | "analytics_leaderboard" | "analytics_time_series" | "count" | "create" | "create_many" | "create_many_from_file" | "delete" | "delete_many" | "export" | "index" | "restore" | "search" | "show" | "update" | "update_many" | "upsert" | "upsert_many";
10
10
 
11
+ /** The operator of a filter condition, as in a record search. */
12
+ export type FilterOperator = "all" | "between" | "contains" | "elem_match" | "ends_with" | "=" | "exists" | ">" | ">=" | "has_value" | "in" | "is" | "is_not" | "is_not_null" | "is_null" | "<" | "<=" | "missing_value" | "mod" | "not" | "!=" | "not_exists" | "not_in" | "regex" | "search" | "starts_with";
13
+
14
+ /** A key that every record has without a field, such as `id`. */
15
+ export type RecordMetaField = "id" | "workspace_id" | "resource_id" | "__meta" | "created_at" | "updated_at" | "deleted_at" | "cascade_key";
16
+
11
17
  /** A declarative resolver tree, for example `{ $type: 'text.slugify', $value: { ... } }`. */
12
18
  export type Resolver = { readonly $type: string; readonly $value?: StaticValue };
13
19
 
package/dist/index.d.ts CHANGED
@@ -1,6 +1,13 @@
1
1
  import './globals';
2
2
  import type { ResourceCapabilities } from './capabilities.generated';
3
- import type { DataApiEndpoint, FieldDefinition, FieldType } from './fields.generated';
3
+ import type {
4
+ DataApiEndpoint,
5
+ FieldDefinition,
6
+ FieldType,
7
+ FilterOperator,
8
+ RecordMetaField,
9
+ Resolver
10
+ } from './fields.generated';
4
11
 
5
12
  // The configuration helpers of file-based workspaces. The workspace build
6
13
  // reads these calls as static data. index.js implements each define* function
@@ -66,6 +73,8 @@ export type {
66
73
  FieldSchemaDefinition,
67
74
  FieldSchemaSetting,
68
75
  FieldType,
76
+ FilterOperator,
77
+ RecordMetaField,
69
78
  RelationFieldOptions,
70
79
  RelationInverse,
71
80
  Resolver
@@ -86,13 +95,79 @@ export type PolicyScope =
86
95
 
87
96
  export type PolicyAccess = 'public' | 'protected';
88
97
 
89
- export type PolicyDefinition = {
98
+ /**
99
+ * One condition of a filter tree, in the shape of a record search filter. The
100
+ * field is a field key or a path, for example `author.id`. The value can be a
101
+ * resolver, for example `{ $type: 'user.current', $value: { key: 'id' } }`
102
+ * for the signed-in member.
103
+ */
104
+ export type FilterCondition = {
105
+ field: string;
106
+ operator: FilterOperator;
107
+ value?: StaticValue | Resolver;
108
+ case_insensitive?: boolean;
109
+ };
110
+
111
+ export type FilterGroup = {
112
+ operator: 'and' | 'or' | 'nor';
113
+ conditions: readonly (FilterGroup | FilterCondition)[];
114
+ };
115
+
116
+ /**
117
+ * A field that a policy lets through, by key. A relation path, for example
118
+ * `teacher.name`, limits the related record to that key. A key alone always
119
+ * shows the field. A `condition` is a resolver that returns true when the
120
+ * field shows.
121
+ */
122
+ export type PolicyFieldKey<TKey extends string = string> = TKey | `${TKey}.${string}`;
123
+
124
+ export type PolicyField<TKey extends string = string> =
125
+ | PolicyFieldKey<TKey>
126
+ | { key: PolicyFieldKey<TKey>; condition?: Resolver };
127
+
128
+ type PolicyBase<TKey extends string> = {
90
129
  name: string;
91
130
  scope: 'all' | readonly PolicyScope[];
92
- access: PolicyAccess;
93
131
  description?: string | null;
132
+ /** A disabled policy grants nothing. Defaults to true. */
133
+ enabled?: boolean;
134
+ /** Limits the records that the policy covers, for example the member's own records. */
135
+ filter?: FilterGroup;
136
+ /**
137
+ * The fields that the policy lets through. A field that the list leaves out
138
+ * is hidden from reads and refused on writes. Without a list, the policy
139
+ * covers every field.
140
+ */
141
+ fields?: readonly PolicyField<TKey>[];
94
142
  };
95
143
 
144
+ /** Grants access to every visitor, signed in or not. */
145
+ export type PublicPolicyDefinition<TKey extends string = string> = PolicyBase<TKey> & {
146
+ access: 'public';
147
+ resource?: never;
148
+ authorizer?: never;
149
+ };
150
+
151
+ /**
152
+ * Grants access to the signed-in members of `resource`, an `authenticatable`
153
+ * resource or the platform staff resource. Without `resource`, only system
154
+ * administrators have access.
155
+ */
156
+ export type ProtectedPolicyDefinition<TKey extends string = string> = PolicyBase<TKey> & {
157
+ access?: 'protected';
158
+ /** The resource that members sign in as, as `Resources.<Name>.slug`. */
159
+ resource?: ResourceReference;
160
+ /**
161
+ * Tests the signed-in member's own record, for example a role. The policy
162
+ * applies only when the member's record matches.
163
+ */
164
+ authorizer?: FilterGroup;
165
+ };
166
+
167
+ export type PolicyDefinition<TKey extends string = string> =
168
+ | PublicPolicyDefinition<TKey>
169
+ | ProtectedPolicyDefinition<TKey>;
170
+
96
171
  export type IndexDefinition<TKey extends string = string> = {
97
172
  fields: readonly TKey[];
98
173
  unique?: boolean;
@@ -134,7 +209,7 @@ export type ResourceDefinition<
134
209
  dataApi?: ResourceDataApi;
135
210
  /** A static resource refuses normal record writes. */
136
211
  static?: boolean;
137
- policies: readonly PolicyDefinition[];
212
+ policies: readonly PolicyDefinition<Extract<keyof TFields, string> | RecordMetaField>[];
138
213
  /**
139
214
  * The platform capabilities of the resource, keyed by capability. A field
140
215
  * reference names a field of this resource by its key. The deploy validates
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@diagonal-hq/cli",
3
- "version": "0.9.0",
3
+ "version": "0.9.1",
4
4
  "description": "The diagonal CLI and the configuration helpers for file-based Diagonal workspaces.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "repository": {