@nocobase/plugin-field-sequence 1.2.12-alpha → 1.3.0-alpha.20240710084543

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/package.json +2 -2
  2. package/dist/client/SequenceFieldProvider.d.ts +0 -10
  3. package/dist/client/index.d.ts +0 -13
  4. package/dist/client/index.js +0 -28
  5. package/dist/client/locale/index.d.ts +0 -11
  6. package/dist/client/sequence.d.ts +0 -267
  7. package/dist/externalVersion.js +0 -23
  8. package/dist/index.d.ts +0 -10
  9. package/dist/index.js +0 -48
  10. package/dist/locale/en-US.json +0 -24
  11. package/dist/locale/es-ES.json +0 -24
  12. package/dist/locale/fr-FR.json +0 -24
  13. package/dist/locale/ko_KR.json +0 -24
  14. package/dist/locale/pt-BR.json +0 -24
  15. package/dist/locale/zh-CN.json +0 -28
  16. package/dist/node_modules/cron-parser/.eslintrc.json +0 -15
  17. package/dist/node_modules/cron-parser/.travis.yml +0 -7
  18. package/dist/node_modules/cron-parser/LICENSE +0 -21
  19. package/dist/node_modules/cron-parser/component.json +0 -11
  20. package/dist/node_modules/cron-parser/index.d.ts +0 -1
  21. package/dist/node_modules/cron-parser/lib/date.js +0 -252
  22. package/dist/node_modules/cron-parser/lib/expression.js +0 -983
  23. package/dist/node_modules/cron-parser/lib/field_compactor.js +0 -70
  24. package/dist/node_modules/cron-parser/lib/field_stringify.js +0 -38
  25. package/dist/node_modules/cron-parser/lib/parser.js +0 -1
  26. package/dist/node_modules/cron-parser/node_modules/luxon/build/amd/luxon.js +0 -8489
  27. package/dist/node_modules/cron-parser/node_modules/luxon/build/cjs-browser/luxon.js +0 -8487
  28. package/dist/node_modules/cron-parser/node_modules/luxon/build/global/luxon.js +0 -8490
  29. package/dist/node_modules/cron-parser/node_modules/luxon/build/global/luxon.min.js +0 -1
  30. package/dist/node_modules/cron-parser/node_modules/luxon/build/node/luxon.js +0 -7522
  31. package/dist/node_modules/cron-parser/node_modules/luxon/package.json +0 -96
  32. package/dist/node_modules/cron-parser/node_modules/luxon/src/datetime.js +0 -2169
  33. package/dist/node_modules/cron-parser/node_modules/luxon/src/duration.js +0 -880
  34. package/dist/node_modules/cron-parser/node_modules/luxon/src/errors.js +0 -61
  35. package/dist/node_modules/cron-parser/node_modules/luxon/src/impl/conversions.js +0 -157
  36. package/dist/node_modules/cron-parser/node_modules/luxon/src/impl/diff.js +0 -80
  37. package/dist/node_modules/cron-parser/node_modules/luxon/src/impl/digits.js +0 -76
  38. package/dist/node_modules/cron-parser/node_modules/luxon/src/impl/english.js +0 -233
  39. package/dist/node_modules/cron-parser/node_modules/luxon/src/impl/formats.js +0 -191
  40. package/dist/node_modules/cron-parser/node_modules/luxon/src/impl/formatter.js +0 -386
  41. package/dist/node_modules/cron-parser/node_modules/luxon/src/impl/invalid.js +0 -14
  42. package/dist/node_modules/cron-parser/node_modules/luxon/src/impl/locale.js +0 -482
  43. package/dist/node_modules/cron-parser/node_modules/luxon/src/impl/regexParser.js +0 -335
  44. package/dist/node_modules/cron-parser/node_modules/luxon/src/impl/tokenParser.js +0 -424
  45. package/dist/node_modules/cron-parser/node_modules/luxon/src/impl/util.js +0 -292
  46. package/dist/node_modules/cron-parser/node_modules/luxon/src/impl/zoneUtil.js +0 -36
  47. package/dist/node_modules/cron-parser/node_modules/luxon/src/info.js +0 -193
  48. package/dist/node_modules/cron-parser/node_modules/luxon/src/interval.js +0 -602
  49. package/dist/node_modules/cron-parser/node_modules/luxon/src/luxon.js +0 -26
  50. package/dist/node_modules/cron-parser/node_modules/luxon/src/luxonFilled.js +0 -13
  51. package/dist/node_modules/cron-parser/node_modules/luxon/src/settings.js +0 -137
  52. package/dist/node_modules/cron-parser/node_modules/luxon/src/zone.js +0 -88
  53. package/dist/node_modules/cron-parser/node_modules/luxon/src/zones/IANAZone.js +0 -191
  54. package/dist/node_modules/cron-parser/node_modules/luxon/src/zones/fixedOffsetZone.js +0 -94
  55. package/dist/node_modules/cron-parser/node_modules/luxon/src/zones/invalidZone.js +0 -53
  56. package/dist/node_modules/cron-parser/node_modules/luxon/src/zones/localZone.js +0 -63
  57. package/dist/node_modules/cron-parser/package.json +0 -1
  58. package/dist/node_modules/cron-parser/test/31_of_month.js +0 -17
  59. package/dist/node_modules/cron-parser/test/bug.js +0 -29
  60. package/dist/node_modules/cron-parser/test/crondate.js +0 -16
  61. package/dist/node_modules/cron-parser/test/crontab.example +0 -7
  62. package/dist/node_modules/cron-parser/test/empty_around_comma.js +0 -22
  63. package/dist/node_modules/cron-parser/test/expression.js +0 -1489
  64. package/dist/node_modules/cron-parser/test/field_compactor.js +0 -250
  65. package/dist/node_modules/cron-parser/test/field_stringify.js +0 -84
  66. package/dist/node_modules/cron-parser/test/fields.js +0 -32
  67. package/dist/node_modules/cron-parser/test/increment_on_first_iteration.js +0 -22
  68. package/dist/node_modules/cron-parser/test/index-ts3.test-d.ts +0 -133
  69. package/dist/node_modules/cron-parser/test/index.test-d.ts +0 -138
  70. package/dist/node_modules/cron-parser/test/leap_year.js +0 -17
  71. package/dist/node_modules/cron-parser/test/parser.js +0 -46
  72. package/dist/node_modules/cron-parser/test/parser_crondate_formats.js +0 -145
  73. package/dist/node_modules/cron-parser/test/parser_day_of_month.js +0 -169
  74. package/dist/node_modules/cron-parser/test/prev_date.js +0 -32
  75. package/dist/node_modules/cron-parser/test/stringify.js +0 -402
  76. package/dist/node_modules/cron-parser/test/timezone.js +0 -422
  77. package/dist/node_modules/cron-parser/types/common.d.ts +0 -131
  78. package/dist/node_modules/cron-parser/types/index.d.ts +0 -45
  79. package/dist/node_modules/cron-parser/types/ts3/index.d.ts +0 -28
  80. package/dist/server/Plugin.d.ts +0 -16
  81. package/dist/server/Plugin.js +0 -133
  82. package/dist/server/collections/sequences.d.ts +0 -10
  83. package/dist/server/collections/sequences.js +0 -99
  84. package/dist/server/fields/sequence-field.d.ts +0 -46
  85. package/dist/server/fields/sequence-field.js +0 -395
  86. package/dist/server/index.d.ts +0 -10
  87. package/dist/server/index.js +0 -48
  88. package/dist/server/migrations/20221207022250-sequence-field-key.d.ts +0 -14
  89. package/dist/server/migrations/20221207022250-sequence-field-key.js +0 -94
  90. package/dist/server/migrations/20240425225438-change-locale-module.d.ts +0 -14
  91. package/dist/server/migrations/20240425225438-change-locale-module.js +0 -51
@@ -1,133 +0,0 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
-
10
- var __create = Object.create;
11
- var __defProp = Object.defineProperty;
12
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
13
- var __getOwnPropNames = Object.getOwnPropertyNames;
14
- var __getProtoOf = Object.getPrototypeOf;
15
- var __hasOwnProp = Object.prototype.hasOwnProperty;
16
- var __export = (target, all) => {
17
- for (var name in all)
18
- __defProp(target, name, { get: all[name], enumerable: true });
19
- };
20
- var __copyProps = (to, from, except, desc) => {
21
- if (from && typeof from === "object" || typeof from === "function") {
22
- for (let key of __getOwnPropNames(from))
23
- if (!__hasOwnProp.call(to, key) && key !== except)
24
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
25
- }
26
- return to;
27
- };
28
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
29
- // If the importer is in node compatibility mode or this is not an ESM
30
- // file that has been converted to a CommonJS file using a Babel-
31
- // compatible transform (i.e. "__esModule" has not been set), then set
32
- // "default" to the CommonJS "module.exports" for node compatibility.
33
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
34
- mod
35
- ));
36
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
37
- var Plugin_exports = {};
38
- __export(Plugin_exports, {
39
- default: () => PluginFieldSequenceServer
40
- });
41
- module.exports = __toCommonJS(Plugin_exports);
42
- var import_crypto = require("crypto");
43
- var import_path = __toESM(require("path"));
44
- var import_util = require("util");
45
- var import_server = require("@nocobase/server");
46
- var import_utils = require("@nocobase/utils");
47
- var import_sequence_field = require("./fields/sequence-field");
48
- const asyncRandomInt = (0, import_util.promisify)(import_crypto.randomInt);
49
- class PluginFieldSequenceServer extends import_server.Plugin {
50
- patternTypes = new import_utils.Registry();
51
- async load() {
52
- const { app, db, options } = this;
53
- db.registerFieldTypes({
54
- sequence: import_sequence_field.SequenceField
55
- });
56
- db.addMigrations({
57
- namespace: "sequence-field",
58
- directory: import_path.default.resolve(__dirname, "migrations"),
59
- context: {
60
- plugin: this
61
- }
62
- });
63
- await this.importCollections(import_path.default.resolve(__dirname, "collections"));
64
- db.on("fields.beforeSave", async (field, { transaction }) => {
65
- if (field.get("type") !== "sequence") {
66
- return;
67
- }
68
- const patterns = (field.get("patterns") || []).filter((p) => p.type === "integer");
69
- if (!patterns.length) {
70
- return;
71
- }
72
- const SequenceRepo = db.getRepository("sequences");
73
- await patterns.reduce(
74
- (promise, p) => promise.then(async () => {
75
- var _a;
76
- if (((_a = p.options) == null ? void 0 : _a.key) == null) {
77
- Object.assign(p, {
78
- options: {
79
- ...p.options,
80
- key: await asyncRandomInt(1 << 16)
81
- }
82
- });
83
- }
84
- }),
85
- Promise.resolve()
86
- );
87
- const sequences = await SequenceRepo.find({
88
- filter: {
89
- field: field.get("name"),
90
- collection: field.get("collectionName"),
91
- key: patterns.map((p) => p.options.key)
92
- },
93
- transaction
94
- });
95
- await patterns.reduce(
96
- (promise, p) => promise.then(async () => {
97
- if (!sequences.find((s) => s.get("key") === p.options.key)) {
98
- await SequenceRepo.create({
99
- values: {
100
- field: field.get("name"),
101
- collection: field.get("collectionName"),
102
- key: p.options.key
103
- },
104
- transaction
105
- });
106
- await field.load({ transaction });
107
- }
108
- }),
109
- Promise.resolve()
110
- );
111
- });
112
- db.on("fields.afterDestroy", async (field, { transaction }) => {
113
- if (field.get("type") !== "sequence") {
114
- return;
115
- }
116
- const patterns = (field.get("patterns") || []).filter((p) => p.type === "integer");
117
- if (!patterns.length) {
118
- return;
119
- }
120
- const SequenceRepo = db.getRepository("sequences");
121
- await SequenceRepo.destroy({
122
- filter: {
123
- field: field.get("name"),
124
- collection: field.get("collectionName"),
125
- key: patterns.map((p) => p.key)
126
- },
127
- transaction
128
- });
129
- });
130
- }
131
- async install() {
132
- }
133
- }
@@ -1,10 +0,0 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
- declare const _default: import("@nocobase/database").CollectionOptions;
10
- export default _default;
@@ -1,99 +0,0 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
-
10
- var __defProp = Object.defineProperty;
11
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
- var __getOwnPropNames = Object.getOwnPropertyNames;
13
- var __hasOwnProp = Object.prototype.hasOwnProperty;
14
- var __export = (target, all) => {
15
- for (var name in all)
16
- __defProp(target, name, { get: all[name], enumerable: true });
17
- };
18
- var __copyProps = (to, from, except, desc) => {
19
- if (from && typeof from === "object" || typeof from === "function") {
20
- for (let key of __getOwnPropNames(from))
21
- if (!__hasOwnProp.call(to, key) && key !== except)
22
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
- }
24
- return to;
25
- };
26
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
- var sequences_exports = {};
28
- __export(sequences_exports, {
29
- default: () => sequences_default
30
- });
31
- module.exports = __toCommonJS(sequences_exports);
32
- var import_database = require("@nocobase/database");
33
- var sequences_default = (0, import_database.defineCollection)({
34
- dumpRules: {
35
- group: "required",
36
- async delayRestore(restorer) {
37
- const app = restorer.app;
38
- const importedCollections = restorer.importedCollections;
39
- const sequenceFields = importedCollections.map((collection) => {
40
- const collectionInstance = app.db.getCollection(collection);
41
- if (!collectionInstance) {
42
- app.logger.warn(`Collection ${collection} not found`);
43
- return [];
44
- }
45
- return [...collectionInstance.fields.values()].filter((field) => field.type === "sequence");
46
- }).flat().filter(Boolean);
47
- const sequencesAttributes = sequenceFields.map((field) => {
48
- const patterns = field.get("patterns");
49
- return patterns.map((pattern) => {
50
- return {
51
- collection: field.collection.name,
52
- field: field.name,
53
- key: pattern.options.key
54
- };
55
- });
56
- }).flat().filter((attr) => attr.collection && attr.field && attr.key);
57
- if (sequencesAttributes.length > 0) {
58
- await app.db.getRepository("sequences").destroy({
59
- filter: {
60
- $or: sequencesAttributes
61
- }
62
- });
63
- }
64
- await restorer.importCollection({
65
- name: "sequences",
66
- clear: false,
67
- rowCondition(row) {
68
- return sequencesAttributes.some((attributes) => {
69
- return row.collection === attributes.collection && row.field === attributes.field && row.key === attributes.key;
70
- });
71
- }
72
- });
73
- }
74
- },
75
- name: "sequences",
76
- shared: true,
77
- fields: [
78
- {
79
- name: "collection",
80
- type: "string"
81
- },
82
- {
83
- name: "field",
84
- type: "string"
85
- },
86
- {
87
- name: "key",
88
- type: "integer"
89
- },
90
- {
91
- name: "current",
92
- type: "bigInt"
93
- },
94
- {
95
- name: "lastGeneratedAt",
96
- type: "date"
97
- }
98
- ]
99
- });
@@ -1,46 +0,0 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
- import { BaseColumnFieldOptions, DataTypes, Field, FieldContext, Model, Transactionable } from '@nocobase/database';
10
- import { Registry } from '@nocobase/utils';
11
- export interface Pattern {
12
- validate?(options: any): string | null;
13
- generate(this: SequenceField, instance: Model, opts: {
14
- [key: string]: any;
15
- }, options: Transactionable): Promise<string> | string;
16
- batchGenerate(this: SequenceField, instances: Model[], values: string[], opts: {
17
- [key: string]: any;
18
- }, options: Transactionable): Promise<void> | void;
19
- getLength(options: any): number;
20
- getMatcher(options: any): string;
21
- update?(this: SequenceField, instance: Model, value: string, options: any, transactionable: Transactionable): Promise<void>;
22
- }
23
- export declare const sequencePatterns: Registry<Pattern>;
24
- interface PatternConfig {
25
- type: string;
26
- title?: string;
27
- options?: any;
28
- }
29
- export interface SequenceFieldOptions extends BaseColumnFieldOptions {
30
- type: 'sequence';
31
- patterns: PatternConfig[];
32
- }
33
- export declare class SequenceField extends Field {
34
- matcher: RegExp;
35
- get dataType(): DataTypes.StringDataTypeConstructor;
36
- constructor(options: SequenceFieldOptions, context: FieldContext);
37
- validate: (instance: Model) => void;
38
- setValue: (instance: Model, options: any) => Promise<void>;
39
- setGroupValue: (instances: Model[], options: any) => Promise<void>;
40
- cleanHook: (_: any, options: any) => void;
41
- match(value: any): RegExpMatchArray;
42
- update(instance: Model, options: any): Promise<void>;
43
- bind(): void;
44
- unbind(): void;
45
- }
46
- export {};
@@ -1,395 +0,0 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
-
10
- var __create = Object.create;
11
- var __defProp = Object.defineProperty;
12
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
13
- var __getOwnPropNames = Object.getOwnPropertyNames;
14
- var __getProtoOf = Object.getPrototypeOf;
15
- var __hasOwnProp = Object.prototype.hasOwnProperty;
16
- var __export = (target, all) => {
17
- for (var name in all)
18
- __defProp(target, name, { get: all[name], enumerable: true });
19
- };
20
- var __copyProps = (to, from, except, desc) => {
21
- if (from && typeof from === "object" || typeof from === "function") {
22
- for (let key of __getOwnPropNames(from))
23
- if (!__hasOwnProp.call(to, key) && key !== except)
24
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
25
- }
26
- return to;
27
- };
28
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
29
- // If the importer is in node compatibility mode or this is not an ESM
30
- // file that has been converted to a CommonJS file using a Babel-
31
- // compatible transform (i.e. "__esModule" has not been set), then set
32
- // "default" to the CommonJS "module.exports" for node compatibility.
33
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
34
- mod
35
- ));
36
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
37
- var sequence_field_exports = {};
38
- __export(sequence_field_exports, {
39
- SequenceField: () => SequenceField,
40
- sequencePatterns: () => sequencePatterns
41
- });
42
- module.exports = __toCommonJS(sequence_field_exports);
43
- var import_database = require("@nocobase/database");
44
- var import_utils = require("@nocobase/utils");
45
- var import_cron_parser = __toESM(require("cron-parser"));
46
- var import_dayjs = __toESM(require("dayjs"));
47
- var import_lodash = __toESM(require("lodash"));
48
- const sequencePatterns = new import_utils.Registry();
49
- sequencePatterns.register("string", {
50
- validate(options) {
51
- if (!(options == null ? void 0 : options.value)) {
52
- return "options.value should be configured as a non-empty string";
53
- }
54
- return null;
55
- },
56
- generate(instance, options) {
57
- return options.value;
58
- },
59
- batchGenerate(instances, values, options) {
60
- instances.forEach((instance, i) => {
61
- values[i] = options.value;
62
- });
63
- },
64
- getLength(options) {
65
- return options.value.length;
66
- },
67
- getMatcher(options) {
68
- return import_lodash.default.escapeRegExp(options.value);
69
- }
70
- });
71
- sequencePatterns.register("integer", {
72
- // validate(options) {
73
- // if (!options?.key) {
74
- // return 'options.key should be configured as an integer';
75
- // }
76
- // return null;
77
- // },
78
- async generate(instance, options, { transaction }) {
79
- const recordTime = instance.get("createdAt") ?? /* @__PURE__ */ new Date();
80
- const { digits = 1, start = 0, base = 10, cycle, key } = options;
81
- const { repository: SeqRepo, model: SeqModel } = this.database.getCollection("sequences");
82
- const lastSeq = await SeqRepo.findOne({
83
- filter: {
84
- collection: this.collection.name,
85
- field: this.name,
86
- key
87
- },
88
- transaction
89
- }) || SeqModel.build({
90
- collection: this.collection.name,
91
- field: this.name,
92
- key
93
- });
94
- let next = start;
95
- if (lastSeq.get("current") != null) {
96
- next = Math.max(lastSeq.get("current") + 1, start);
97
- const max = Math.pow(base, digits) - 1;
98
- if (next > max) {
99
- next = start;
100
- }
101
- if (cycle) {
102
- const interval = import_cron_parser.default.parseExpression(cycle, { currentDate: lastSeq.get("lastGeneratedAt") });
103
- const nextTime = interval.next();
104
- if (recordTime.getTime() >= nextTime.getTime()) {
105
- next = start;
106
- }
107
- }
108
- }
109
- lastSeq.set({
110
- current: next,
111
- lastGeneratedAt: recordTime
112
- });
113
- await lastSeq.save({ transaction });
114
- return next.toString(base).padStart(digits, "0");
115
- },
116
- getLength({ digits = 1 } = {}) {
117
- return digits;
118
- },
119
- getMatcher(options = {}) {
120
- const { digits = 1, base = 10 } = options;
121
- const chars = "0123456789abcdefghijklmnopqrstuvwxyz".slice(0, base);
122
- return `[${chars}]{${digits}}`;
123
- },
124
- async batchGenerate(instances, values, options, { transaction }) {
125
- const { name, patterns } = this.options;
126
- const { digits = 1, start = 0, base = 10, cycle, key } = options;
127
- const { repository: SeqRepo, model: SeqModel } = this.database.getCollection("sequences");
128
- const lastSeq = await SeqRepo.findOne({
129
- filter: {
130
- collection: this.collection.name,
131
- field: this.name,
132
- key
133
- },
134
- transaction
135
- }) || SeqModel.build({
136
- collection: this.collection.name,
137
- field: this.name,
138
- key
139
- });
140
- instances.forEach((instance, i) => {
141
- const recordTime = instance.get("createdAt") ?? /* @__PURE__ */ new Date();
142
- const value = instance.get(name);
143
- if (value != null && this.options.inputable) {
144
- const matcher = this.match(value);
145
- if (matcher) {
146
- const patternIndex = patterns.indexOf(options);
147
- const number = Number.parseInt(matcher[patternIndex + 1], base);
148
- if (lastSeq.get("current") == null) {
149
- lastSeq.set({
150
- current: number,
151
- lastGeneratedAt: recordTime
152
- });
153
- } else {
154
- if (number > lastSeq.get("current")) {
155
- lastSeq.set({
156
- current: number,
157
- lastGeneratedAt: recordTime
158
- });
159
- }
160
- }
161
- }
162
- } else {
163
- let next = start;
164
- if (lastSeq.get("current") != null) {
165
- next = Math.max(lastSeq.get("current") + 1, start);
166
- const max = Math.pow(base, digits) - 1;
167
- if (next > max) {
168
- next = start;
169
- }
170
- if (cycle) {
171
- const interval = import_cron_parser.default.parseExpression(cycle, { currentDate: lastSeq.get("lastGeneratedAt") });
172
- const nextTime = interval.next();
173
- if (recordTime.getTime() >= nextTime.getTime()) {
174
- next = start;
175
- }
176
- }
177
- }
178
- lastSeq.set({
179
- current: next,
180
- lastGeneratedAt: recordTime
181
- });
182
- values[i] = next.toString(base).padStart(digits, "0");
183
- }
184
- });
185
- await lastSeq.save({ transaction });
186
- },
187
- async update(instance, value, options, { transaction }) {
188
- const recordTime = instance.get("createdAt") ?? /* @__PURE__ */ new Date();
189
- const { digits = 1, start = 0, base = 10, cycle, key } = options;
190
- const SeqRepo = this.database.getRepository("sequences");
191
- const lastSeq = await SeqRepo.findOne({
192
- filter: {
193
- collection: this.collection.name,
194
- field: this.name,
195
- key
196
- },
197
- transaction
198
- });
199
- const current = Number.parseInt(value, base);
200
- if (!lastSeq) {
201
- return SeqRepo.create({
202
- values: {
203
- collection: this.collection.name,
204
- field: this.name,
205
- key,
206
- current,
207
- lastGeneratedAt: recordTime
208
- },
209
- transaction
210
- });
211
- }
212
- if (lastSeq.get("current") == null) {
213
- return lastSeq.update(
214
- {
215
- current,
216
- lastGeneratedAt: recordTime
217
- },
218
- { transaction }
219
- );
220
- }
221
- if (cycle) {
222
- const interval = import_cron_parser.default.parseExpression(cycle, { currentDate: lastSeq.get("lastGeneratedAt") });
223
- const nextTime = interval.next();
224
- if (recordTime.getTime() >= nextTime.getTime()) {
225
- lastSeq.set({
226
- current,
227
- lastGeneratedAt: recordTime
228
- });
229
- } else {
230
- if (current > lastSeq.get("current")) {
231
- lastSeq.set({
232
- current,
233
- lastGeneratedAt: recordTime
234
- });
235
- }
236
- }
237
- } else {
238
- if (current > lastSeq.get("current")) {
239
- lastSeq.set({
240
- current,
241
- lastGeneratedAt: recordTime
242
- });
243
- }
244
- }
245
- return lastSeq.save({ transaction });
246
- }
247
- });
248
- sequencePatterns.register("date", {
249
- generate(instance, options) {
250
- return (0, import_dayjs.default)(instance.get((options == null ? void 0 : options.field) ?? "createdAt")).format((options == null ? void 0 : options.format) ?? "YYYYMMDD");
251
- },
252
- batchGenerate(instances, values, options) {
253
- const { field, inputable } = options;
254
- instances.forEach((instance, i) => {
255
- if (!inputable || instance.get(field ?? "createdAt") == null) {
256
- values[i] = sequencePatterns.get("date").generate.call(this, instance, options);
257
- }
258
- });
259
- },
260
- getLength(options) {
261
- var _a;
262
- return ((_a = options.format) == null ? void 0 : _a.length) ?? 8;
263
- },
264
- getMatcher(options = {}) {
265
- var _a;
266
- return `.{${((_a = options == null ? void 0 : options.format) == null ? void 0 : _a.length) ?? 8}}`;
267
- }
268
- });
269
- class SequenceField extends import_database.Field {
270
- matcher;
271
- get dataType() {
272
- return import_database.DataTypes.STRING;
273
- }
274
- constructor(options, context) {
275
- super(options, context);
276
- if (!options.patterns || !options.patterns.length) {
277
- throw new Error("at least one pattern should be defined for sequence type");
278
- }
279
- options.patterns.forEach((pattern) => {
280
- const P = sequencePatterns.get(pattern.type);
281
- if (!P) {
282
- throw new Error(`pattern type ${pattern.type} is not registered`);
283
- }
284
- if (P.validate) {
285
- const error = P.validate(pattern.options);
286
- if (error) {
287
- throw new Error(error);
288
- }
289
- }
290
- });
291
- const patterns = options.patterns.map(({ type, options: options2 }) => sequencePatterns.get(type).getMatcher(options2));
292
- this.matcher = new RegExp(`^${patterns.map((p) => `(${p})`).join("")}$`, "i");
293
- }
294
- validate = (instance) => {
295
- const { name, inputable, match } = this.options;
296
- const value = instance.get(name);
297
- if (value != null && inputable && match && !this.match(value)) {
298
- throw new import_database.ValidationError("sequence pattern not match", [
299
- new import_database.ValidationErrorItem(
300
- `input value of ${name} field not match the sequence pattern (${this.matcher.toString()}) which is required`,
301
- "validation error",
302
- // NOTE: type should only be this which in sequelize enum set
303
- name,
304
- value,
305
- instance,
306
- "sequence_pattern_not_match",
307
- name,
308
- []
309
- )
310
- ]);
311
- }
312
- };
313
- setValue = async (instance, options) => {
314
- var _a;
315
- if ((_a = options.skipIndividualHooks) == null ? void 0 : _a.has(`${this.collection.name}.beforeCreate.${this.name}`)) {
316
- return;
317
- }
318
- const { name, patterns, inputable } = this.options;
319
- const value = instance.get(name);
320
- if (value != null && inputable) {
321
- return this.update(instance, options);
322
- }
323
- const results = await patterns.reduce(
324
- (promise, p) => promise.then(async (result) => {
325
- const item = await sequencePatterns.get(p.type).generate.call(this, instance, p.options, options);
326
- return result.concat(item);
327
- }),
328
- Promise.resolve([])
329
- );
330
- instance.set(name, results.join(""));
331
- };
332
- setGroupValue = async (instances, options) => {
333
- if (!instances.length) {
334
- return;
335
- }
336
- if (!options.skipIndividualHooks) {
337
- options.skipIndividualHooks = /* @__PURE__ */ new Set();
338
- }
339
- options.skipIndividualHooks.add(`${this.collection.name}.beforeCreate.${this.name}`);
340
- const { name, patterns, inputable } = this.options;
341
- const array = Array(patterns.length).fill(null).map(() => Array(instances.length));
342
- await patterns.reduce(
343
- (promise, p, i) => promise.then(
344
- () => sequencePatterns.get(p.type).batchGenerate.call(this, instances, array[i], p.options ?? {}, options)
345
- ),
346
- Promise.resolve()
347
- );
348
- instances.forEach((instance, i) => {
349
- const value = instance.get(name);
350
- if (!inputable || value == null) {
351
- instance.set(this.name, array.map((a) => a[i]).join(""));
352
- }
353
- });
354
- };
355
- cleanHook = (_, options) => {
356
- options.skipIndividualHooks.delete(`${this.collection.name}.beforeCreate.${this.name}`);
357
- };
358
- match(value) {
359
- return typeof value === "string" ? value.match(this.matcher) : null;
360
- }
361
- async update(instance, options) {
362
- const { name, patterns } = this.options;
363
- const matched = this.match(instance.get(name));
364
- if (matched) {
365
- await matched.slice(1).map((_, i) => sequencePatterns.get(patterns[i].type).update).reduce(
366
- (promise, update, i) => promise.then(() => {
367
- if (!update) {
368
- return;
369
- }
370
- return update.call(this, instance, matched[i + 1], patterns[i].options, options);
371
- }),
372
- Promise.resolve()
373
- );
374
- }
375
- }
376
- bind() {
377
- super.bind();
378
- this.on("beforeValidate", this.validate);
379
- this.on("beforeCreate", this.setValue);
380
- this.on("beforeBulkCreate", this.setGroupValue);
381
- this.on("afterBulkCreate", this.cleanHook);
382
- }
383
- unbind() {
384
- super.unbind();
385
- this.off("beforeValidate", this.validate);
386
- this.off("beforeCreate", this.setValue);
387
- this.off("beforeBulkCreate", this.setGroupValue);
388
- this.off("afterBulkCreate", this.cleanHook);
389
- }
390
- }
391
- // Annotate the CommonJS export names for ESM import in node:
392
- 0 && (module.exports = {
393
- SequenceField,
394
- sequencePatterns
395
- });
@@ -1,10 +0,0 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
- export * from './fields/sequence-field';
10
- export { default } from './Plugin';